java设计模式之单例模式

 1 /*
 2  * 单例模式
 3  */
 4 /*第一种写法//先初始化对象,成为:饿汉式(原则:定义时,建议用)
 5  * 已经创建了对象
 6  class Single {
 7  private static Single s = new Single();
 8 
 9  private Single() {
10  }
11 
12  private static Single getInstance() {
13  return s;
14  }
15 
16  }*/
17 //第二种写法,对象被调用时,才初始化(才创建对象),也叫做对象的延时加载,也叫做:懒汉式(面试多见)
18 class Single {
19     private static Single s = null;
20 
21     private Single() {
22     }
23 
24     private static synchronized Single getInstance() {//synchronized同步
25         
26         if (s == null)
27             //--》a
28             //--》b
29             s = new Single();
30         return s;
31         /**解决方案
32          * if(s == null){
33          *         synchronized(Single.class){//加锁
34          *         if(s == null)
35          *             s = new Single();
36          *         }
37          * }
38          * return s;
39          */
40     }
41 
42 }
43 
44 public class SingleDome {
45 
46     public static void main(String[] args) {
47 
48     }
49 
50 }
Single
原文地址:https://www.cnblogs.com/sxmcACM/p/3475855.html