在域上运用延迟初始化占位类模式
public class InstanceLazy {
private Integer value;
private Integer heavy;
public InstanceLazy(Integer value) {
super();
this.value = value;
}
private static class InstanceHolder{
public static Integer val = new Integer(100);
}
public Integer getValue() {
return value;
}
public Integer getVal() {
return InstanceHolder.val;
}
}
懒汉式-双重检查
public class SingleDcl {
private volatile static SingleDcl singleDcl;
private SingleDcl(){
}
public static SingleDcl getInstance(){
if (singleDcl == null){
System.out.println(Thread.currentThread()+" is null");
synchronized(SingleDcl.class){
if (singleDcl == null){
System.out.println(Thread.currentThread()+" is null");
singleDcl = new SingleDcl();
}
}
}
return singleDcl;
}
}
饿汉式-枚举
public class SingleEHan {
private SingleEHan(){}
private static SingleEHan singleDcl = new SingleEHan();
}
懒汉式-延迟初始化占位类模式
public class SingleInit {
private SingleInit(){}
private static class InstanceHolder{
private static SingleInit instance = new SingleInit();
}
public static SingleInit getInstance(){
return InstanceHolder.instance;
}
}
懒汉式 - synchronized 加锁
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}