Singleton 模式详解
下面是我们常见的Singleton的写法
package example.designmodel.singleton; public class Singleton1 { private static Singleton1 instance; public Singleton1(){ } public static Singleton1 getinstance(){ if(instance == null){ instance = new Singleton1(); } return instance; } }
public class Singleton2 { private static Singleton2 instance; public Singleton2(){ } public static synchronized Singleton2 getinstance(){ if(instance == null){ instance = new Singleton2(); } return instance; } }
public class Singleton3 { private static Singleton3 instance = new Singleton3(); public Singleton3(){ } public static Singleton3 getinstance(){ return instance; } }
package example.designmodel.singleton; public class Singleton4 { private volatile static Singleton4 instance; public Singleton4(){ } public static Singleton4 getinstance(){ if(instance == null){ synchronized(Singleton4.class){ if(instance == null){ instance = new Singleton4(); } } } return instance; } }