Java设计模式-单例模式

 1     /**
 2      * 一种错误的单例写法,线程不安全
 3      */
 4     private static Singleton uniqueSingleton;
 5 
 6     private Singleton() {
 7     }
 8 
 9     public static Singleton getInstance() {
10         if (uniqueSingleton == null) {
11             uniqueSingleton = new Singleton();
12         }
13 
14         return uniqueSingleton;
15     }
16 
17     /**
18      * 线程安全的懒加载,影响效率,JVM不保证执行顺序
19      */
20     private static Singleton uniqueSingleton;
21 
22     private Singleton() {
23 
24     }
25 
26     public static synchronized Singleton getInstance() {
27         if (uniqueSingleton == null) {
28             uniqueSingleton = new Singleton();
29         }
30 
31         return uniqueSingleton;
32     }
33 
34     /**
35      * 急加载模式,线程安全,代码简单
36      */
37     private final static Singleton singleton = new Singleton();
38 
39     private Singleton() {
40 
41     }
42 
43     public static Singleton getInstance() {
44         return singleton;
45     }
46 
47     /**
48      * 懒加载,双重锁保证,线程安全
49      */
50     private static volatile Singleton singleton;
51 
52     private Singleton() {
53     }
54 
55     private static Singleton getInstance() {
56         if (singleton == null) {
57             synchronized (Singleton.class) {
58                 if (singleton == null) {
59                     return new Singleton();
60                 }
61             }
62         }
63         return singleton;
64     }
65 
66     /**
67      * 懒加载的内部类写法,线程安全,懒加载
68      */
69     private static class SingletonHolder {
70         private final static Singleton singleton = new Singleton();
71     }
72 
73     private Singleton() {
74     }
75 
76     public static Singleton getInstance() {
77         return SingletonHolder.singleton;
78     }

 

posted @ 2018-03-12 23:56  Vongfong  阅读(121)  评论(0)    收藏  举报