单例模式确保某个类只有一个实例,而且自行实例化并向整个系统提供这个实例。
单例模式有三个要点:
1.某个类只有一个实例
2.这个类自行创建该实例
3.这个类自行向整个系统提供这个实例
多台电脑公用的打印机就是现实世界中单例模式的例子。
恶汉式单例模式
public class EagerSingleton{
	private EagerSingleton(){		
	}
	
	private static final EagerSingleton instance = new EagerSingleton();
	
	public static EagerSingleton getInstance(){
		return instance;
	}
}
懒汉式单例模式
public class LazySingleton{
	private LazySingleton(){		
	}
	
	private static LazySingleton instance = null;
	
	public synchronized static LazySingleton getInstance(){
		if(instance == null){
			instance = new LazySingleton();
		}
		return instance;
	}
}
原文:http://www.cnblogs.com/lnlvinso/p/3795438.html