单例模式
一、饿汉式
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();
}
}