(1)双检查
if(instance == null){//一次检查
synchronized (MySingleton.class) {
if(instance == null){//二次检查
instance = new MySingleton();
}
}
(2)静态代码块
private static MySingleton instance = null;
private MySingleton(){}
static{
instance = new MySingleton();
}
public static MySingleton getInstance() {
return instance;
}
(3)静态内置类
private static class MySingletonHandler{
private static MySingleton instance = new MySingleton();
}
private MySingleton(){}
public static MySingleton getInstance() {
return MySingletonHandler.instance;
}
(4)枚举类型
public enum EnumFactory{
singletonFactory;
private MySingleton instance; private EnumFactory(){//枚举类的构造方法在类加载是被实例化
instance = new MySingleton();
}
public MySingleton getInstance(){
return instance;
}
}
class MySingleton{//需要获实现单例的类,比如数据库连接Connection
public MySingleton(){}
}