标签:nal 效率 nbsp color void 注意 volatil style public
什么是单例模式
单例模式是在程序中,一个类保证只有一个实例,并提供统一的访问入口。
为什么要用单例模式
单例的实现方式
1 public class Singleton { 2 3 private static Singleton singleton = new Singleton(); 4 5 private Singleton(){} 6 7 public static Singleton getInstance(){ 8 return singleton; 9 } 10 }
饿汉静态代码块形势
1 public class Singleton { 2 3 private static Singleton singleton; 4 static { 5 singleton = new Singleton(); 6 } 7 private Singleton(){} 8 9 public static Singleton getInstance(){ 10 return singleton; 11 } 12 }
1 public class Singleton { 2 3 private static Singleton singleton; 4 private Singleton(){} 5 6 public static Singleton getInstance(){ 7 if (singleton == null){ 8 return singleton = new Singleton(); 9 } 10 return singleton; 11 } 12 }
1 public class Singleton { 2 3 private static Singleton singleton; 4 private Singleton(){} 5 6 public static synchronized Singleton getInstance(){ 7 if (singleton == null){ 8 return singleton = new Singleton(); 9 } 10 return singleton; 11 } 12 }
1 public class Singleton { 2 /**由于 return singleton = new Singleton(); 这行代码在JVM中会分为三步处理 3 * 1.给singleton分配内存空间 4 * 2.调用singleton的构造函数开初始化 5 * 3.将singleton对象指向分配的内存空间(这步执行了就singleton就不是null了) 6 * 7 * 由于CPU会对这三个步骤重排序,如果顺序是1 3 2,那么就可能出现singleton就不是空的,但并没有初始化singleton 8 * 这样第二个线程可能拿到的就是为初始化的singleton,所以使用volatile来修饰singleton,防止重排序的问题 9 */ 10 private static volatile Singleton singleton; 11 private Singleton(){} 12 13 public static Singleton getInstance(){ 14 if (singleton == null){ 15 synchronized (Singleton.class) { 16 if (singleton == null) { 17 return singleton = new Singleton(); 18 } 19 } 20 } 21 return singleton; 22 } 23 }
1 public class Singleton { 2 3 private static class SingletonInstance{ 4 private static final Singleton singleton = new Singleton(); 5 } 6 private Singleton(){} 7 8 public static Singleton getInstance(){ 9 return SingletonInstance.singleton; 10 } 11 }
1 public enum Singleton{ 2 INSTANCE; 3 public void whateverMethod(){ 4 } 5 }
标签:nal 效率 nbsp color void 注意 volatil style public
原文地址:https://www.cnblogs.com/aaronzheng/p/12111931.html