单例模式就是说无论程序如何运行,采用单例设计模式永远只会有一个实例化对象产生
(1)将采用单例设计模式的构造方法私有化。
(2)在其内部产生该类的实例化对象,并将其封装成private static类型。
(3)定义一个静态方法返回该类的示例。
1 /** 2 * 3 * 单例模式的实现:饿汉式,线程安全 但效率比较低 4 */ 5 public class SingletonTest { 6 7 private SingletonTest() { 8 } 9 10 private static final SingletonTest instance = new SingletonTest(); 11 12 public static SingletonTest getInstancei() { 13 return instance; 14 } 15 16 } 17 18 19 /** 20 * 单例模式的实现:饱汉式,非线程安全 21 * 22 */ 23 public class SingletonTest { 24 private SingletonTest() { 25 } 26 27 private static SingletonTest instance; 28 29 public static SingletonTest getInstance() { 30 if (instance == null) 31 instance = new SingletonTest(); 32 return instance; 33 } 34 } 35 36 37 /** 38 * 线程安全,但是效率非常低 39 * @author vanceinfo 40 * 41 */ 42 public class SingletonTest { 43 private SingletonTest() { 44 } 45 46 private static SingletonTest instance; 47 48 public static synchronized SingletonTest getInstance() { 49 if (instance == null) 50 instance = new SingletonTest(); 51 return instance; 52 } 53 } 54 55 /** 56 * 线程安全 并且效率高 57 * 58 */ 59 public class SingletonTest { 60 private static SingletonTest instance; 61 62 private SingletonTest() { 63 } 64 65 public static SingletonTest getIstance() { 66 if (instance == null) { 67 synchronized (SingletonTest.class) { 69 instance = new SingletonTest(); 71 } 72 } 73 return instance; 74 } 75 }
原文:https://www.cnblogs.com/ivy-xu/p/12401306.html