之前也有同学提到过单例模式,常用的有饿汉和懒汉模式这两种,于是就去找了相关的资料,发现有7种方法可以实现单例模式。话不多少,进入正题
第一种,线程不安全(懒汉模式)
public class Singleton1 {
private static Singleton1 instance;
private Singleton1(){}
public static Singleton1 getInstance(){
if(instance == null){
instance = new Singleton1();
}
return instance;
}
}
第二种,线程安全(懒汉模式)
public class Singleton2 {
private static Singleton2 instance;
private Singleton2(){}
public static synchronized Singleton2 getInstance(){
if(instance == null){
instance = new Singleton2();
}
return instance;
}
}
第三种,线程安全(饿汉模式)
public class Singleton3 {
private static Singleton3 instance = new Singleton3();
private Singleton3(){}
public static synchronized Singleton3 getInstance(){
return instance;
}
}
第四种,线程安全(饿汉模式)
public class Singleton4 {
private static Singleton4 instance ;
static {
instance = new Singleton4();
}
private Singleton4(){}
public static synchronized Singleton4 getInstance(){
return instance;
}
}
第五种,线程安全(静态内部类)
public class Singleton5 {
private Singleton5(){}
public static synchronized Singleton5 getInstance(){
return SingletonHolder.instance;
}
private static class SingletonHolder{
private static Singleton5 instance = new Singleton5();
}
}
第六种,线程安全(枚举类)
public enum Singleton6 { INSTANCE; public void whateverMethod(){} }第七种,线程安全(双重校验模式)public class Singleton7 { private static Singleton7 instance; private Singleton7(){} public static synchronized Singleton7 getInstance(){ if(instance == null){ synchronized (Singleton7.class){ if(instance ==null){ instance = new Singleton7(); } } } return instance; }
}
|
|