一. 定义
- 单例模式确保一个类只有一个实例,而且自行实例化并向整个系统提供这个单例,这个类称为单例类,他提供全局访问的方法。
二. 模式结构

- 单例类的构造函数为私有
- 提供一个自身的静态私有成员变量
- 提供一个公有的静态工厂方法
三. 实例
1. 饿汉式

public class EagerSingleton {
private static final EagerSingleton instance=new EagerSingleton();
private EagerSingleton(){}
public static EagerSingleton getInstance() {
return instance;
}
}
2. 懒汉式
- 单例类在第一次被引用时实例化自己

public class LazySingleton {
private static LazySingleton instance=null;
private LazySingleton(){}
synchronized public static LazySingleton getInstance() {
if(instance==null) {
instance=new LazySingleton();
}
return instance;
}
}
3. Client
public class Client
{
public static void main(String[] args) throws Exception
{
LazySingleton ls1=LazySingleton.getInstance();
LazySingleton ls2=LazySingleton.getInstance();
System.out.println(ls1==ls2);
}
}