Fork me on GitHub

设计模式之Singleton

 1 class Singleton {
 2     
 3     private Singleton() {
 4     }
 5     
 6     private static Singleton instance;
 7     
 8     // v0.1
 9 //    public static Singleton getInstance(){
10 //        if(instance==null) instance=new Singleton();
11 //        return instance;
12 //    }
13 
14     // v0.2
15 //    //Double-check singleton 
16 //    public static Singleton getInstance() {
17 //        if(instance==null) {
18 //            synchronized (Singleton.class) {
19 //                if(instance==null) instance = new Singleton();
20 //            }
21 //        }
22 //        return instance;
23 //    }
24     
25     // v0.3
26     private static class SingletonHolder{
27         static final Singleton INSTANCE=new Singleton();
28     }
29     
30     public static Singleton getInstance(){
31         return SingletonHolder.INSTANCE;
32     }
33     
34 }

 

posted @ 2016-09-02 14:19  CC11001100  阅读(158)  评论(0编辑  收藏  举报