饿汉模式:
//线程安全,调用效率高,但是不能延时加载
class Hungry {
private static Hungry obj = new Hungry();
private Hungry () {}
public static Hungry getInstance(){
return obj;
}
}
懒汉模式:
//方法同步,调用效率低
class Lazy0 {
private static Lazy obj = null;
private Lazy () {}
public static synchronized Lazy getInstance() {
if(obj==null){
obj=new Lazy0();
}
return obj;
}
}
//DCL也就是双重锁判断机制(由于JVM底层模型原因,偶尔会出问题,不建议使用)
class Lazy {
private static Lazy obj = null;
private Lazy () {}
public static Lazy getInstance() {
if (obj == null) {
synchronized (Lazy.class) {
if(obj == null) {
obj = new Lazy();
}
}
}
return obj;
}
}
内部实现类:
//静态内部类实现模式(线程安全,调用效率高,可以延时加载
public class Singleton {
private Singleton{}
public Singleton getInstance() {
return SingletonCreater.obj
}
private static class SingletonCreater () {
priavte static final Singleton obj = new Singleton();
}
}