JavaSE:单例设计模式(懒汉式)

1.  懒汉式

 1 public static Singleton {
 2 
 3     // 2. 声明本类类型的引用,指向本类类型的对象
 4     //    使用private static 关键字修饰
 5     private static Singleton sin = null;
 6 
 7     // 1. 私有化构造方法,使用private关键字修饰
 8     private Singleton(){}
 9 
10     // 3. 提供公有的get方法,负责将sin对象返回出去
11     //    使用public static 关键字修饰
// 缺点: 没有进行线程同步的处理, 可能出现创建多个Singleton对象的情况(违背单例模式)
12 public static Singleton getInstance() { 13 if(null == sin){ 14 sin = new Singleton(); 15 } 16 return sin; 17 } 18 }

2.  懒汉式 (线程同步)

 1 public class Singleton {
 2 
 3     // 2.声明本类类型的引用指向本类类型的对象并使用private static关键字修饰
 4     private static Singleton sin = null;
 5 
 6     // 1.私有化构造方法,使用private关键字修饰
 7     private Singleton() {}
 8 
 9     // 3.提供公有的get方法负责将上述对象返回出去,使用public static关键字修饰
10     public static /*方法一: synchronized*/ Singleton getInstance() {
11         /*方法二: synchronized (Singleton.class) {
12             if (null == sin) {
13                 sin = new Singleton();
14             }
15             return sin;
16         }*/

       // 方法三(优化):
       // 如果sin对象未创建 ---> 加锁 ---> 创建sin对象 ---> 解锁 ---> 返回sin对象   17 if (null == sin) { 18 synchronized (Singleton.class) { 19 if (null == sin) { 20 sin = new Singleton(); 21 } 22 } 23 }
       // 如果sin对象已创建 ---> 直接返回sin对象
24 return sin; 25 } 26 }
原文地址:https://www.cnblogs.com/JasperZhao/p/14953270.html