单例模式几种不同实现方式?
单例模式,是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中,应用该模式的一个类只有一个实例。即一个类只有一个对象实例。
目录
第一种(懒汉模式,线程不安全)
public class SingletonDemo1 {
private static SingletonDemo1 instance;
private SingletonDemo1(){}
public static SingletonDemo1 getInstance(){
if (instance == null) {
instance = new SingletonDemo1();
}
return instance;
}
}
第二种(懒汉模式,线程安全)
public class SingletonDemo2 {
private static SingletonDemo2 instance;
private SingletonDemo2(){}
public static synchronized SingletonDemo2 getInstance(){
if (instance == null) {
instance = new SingletonDemo2();
}
return instance;
}
}
第三种(饿汉模式)
public class SingletonDemo3 {
private static SingletonDemo3 instance = new SingletonDemo3();
private SingletonDemo3(){}
public static SingletonDemo3 getInstance(){
return instance;
}
}
第四种(饿汉模式,变种)
public class SingletonDemo4 {
private static SingletonDemo4 instance = null;
static{
instance = new SingletonDemo4();
}
private SingletonDemo4(){}
public static SingletonDemo4 getInstance(){
return instance;
}
}
第五种(静态内部类)
public class SingletonDemo5 {
private static class SingletonHolder{
private static final SingletonDemo5 instance = new SingletonDemo5();
}
private SingletonDemo5(){}
public static final SingletonDemo5 getInsatance(){
return SingletonHolder.instance;
}
}
第六种(枚举)
public class SingletonDemo6 {
private SingletonDemo6() {}
public static SingletonDemo6 getInstance() {
return Singleton.INSTANCE.getInstance();
}
private static enum Singleton {
INSTANCE;
private SingletonDemo6 singleton;
private Singleton() {
singleton = new SingletonDemo6();
}
public SingletonDemo6 getInstance() {
return singleton;
}
}
}
第七种(双重校验锁)
public class SingletonDemo7 {
private volatile static SingletonDemo7 singletonDemo7;
private SingletonDemo7(){}
public static SingletonDemo7 getSingletonDemo7(){
if (singletonDemo7 == null) {
synchronized (SingletonDemo7.class) {
if (singletonDemo7 == null) {
singletonDemo7 = new SingletonDemo7();
}
}
}
return singletonDemo7;
}
}