创建型模式 --- 单例
2019-06-19 本文已影响0人
十二找十三
1.懒汉式,线程不安全
public class Singleton{
private Singleton() {}
private static Singleton instance;
public static Singleton getInstance(){
if (null == instance){
instance = new Singleton();
}
return instance;
}
}
2.懒汉式,线程安全
public class Singleton{
private Singleton() {}
private static Singleton instance;
public static synchronized Singleton getInstance(){
if (null == instance){
instance = new Singleton();
}
return instance;
}
}
3.饿汉式,线程安全
public class Singleton{
private Singleton() {}
private static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
}
4.枚举,线程安全
public enum Singleton {
INSTANCE;
public void whateverMethod() {
}
}
5.双检锁/双重校验锁
public class Singleton {
private volatile static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton() {
if (null == singleton) {
synchronized (Singleton.class) {
if (null == singleton) {
singleton = new Singleton();
}
}
}
return singleton;
}
}