單例模式
一溶浴、餓漢式
class Test {
private static Test test = new Test();
private Test() {
System.out.println("Test ");
}
public static Test getTest() {
return test;
}
}
二乍迄、懶漢式
public class Singleton {
private static volatile Singleton singleton = null;
private Singleton(){}
public static Singleton getSingleton(){
if(singleton == null){
synchronized (Singleton.class){
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
三、登記者模式【最牛逼的寫法戳葵、推薦使用】
/**
* 最牛逼的單利模式
*/
class Singleton {
private Singleton() {}
public static Singleton getInstance() {
return Holder.SINGLETON;
}
private static class Holder {
public static final Singleton SINGLETON = new Singleton();
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者