---
title: "设计模式----单例模式"
author: "biansutao"
date: "2009-02-16T11:10:35Z"
tags: ["设计模式"]
slug: "untitled"
draft: false
lastmod: "2009-02-16T14:30:02Z"
id: 333390
url: "https://biansutao.iteye.com/blog/333390"
---

```
package com.nstars.rpc;

public class Singleton {
	/*	饿汉式单例模式 缺点：未实现延迟初始化。 */
/*	private static Singleton singleton = new Singleton();
	
	private Singleton(){
		
	}
	
	public static Singleton getInstance(){
		return singleton;
	}*/
	 /*	饿汉式单例模式	*/
	/*	懒汉式单例模式 缺点:同步资源消耗太大。 */
/*	private static Singleton singleton = null;
	private Singleton(){
		
	}
	public synchronized static Singleton getInstance(){
		if(singleton == null){
			singleton = new Singleton();
		}
		return singleton;
	}*/
	/*	懒汉式单例模式	*/
	/*	double-check式单例 */
	private static volatile Singleton singleton = null;
	private Singleton(){
		
	}
	public static Singleton getInstance(){
		if(singleton == null){
			synchronized(Singleton.class){
				if(singleton == null){
					singleton = new Singleton();
				}
			}
		}
		return singleton;
	}
	
	/*	double-check式单例	*/

}
```

 

 可以参考这一篇文章

[http://www.iteye.com/topic/60179](http://www.iteye.com/topic/60179)

或者是Head First 设计模式中关于单例模式的讲解。