关于单例模式

今天去中国银行面试。。。面试官问我对设计模式有什么了解,我就说我最近的项目中自己用单例模式进行了读配置文件。他就让我说说怎么实现,我心中暗喜,这多简单啊。于是就按照饿汉模式说了一遍。。本以为这个问题就这么结束了。可是他突然说,你这种方法不能保证一定是单例的。我楞了。。。于是他说出了双重检测。这个我真是没听说过。面试完了我倍感打击。一个简单的单例模式,没想到让我栽了。不过提醒了我,以后这些东西一定要多看看。不能以为自己做出来了就是OK的。

上网查过以后,发现原来单例实现不只是原来的懒汉式,饿汉式什么的。

1,预先加载

  • class S1 {  
  •     private S1() {  
  •         System.out.println("ok1");  
  •     }  
  •  
  •  
  •     private static S1 instance = new S1();  
  •  
  •     public static S1 getInstance() {  
  •         return instance;  
  •     }  

2,用到时再加载

  • class S2 {  
  •     private S2() {  
  •         System.out.println("ok2");  
  •     }  
  •  
  •     private static S2 instance = null;  
  •  
  •     public static synchronized S2 getInstance() {  
  •         if (instance == null) instance = new S2();  
  •         return instance;  
  •     }  

3,双重检测

  • class S3 {  
  •     private S3() {  
  •         System.out.println("ok3");  
  •     }  
  •  
  •     privatestatic S3 instance = null;  
  •  
  •     publicstatic S3 getInstance() {  
  •         if (instance == null) {  
  •             synchronized (S3.class) {  
  •                 if (instance == null)  
  •                     instance = new S3();  
  •             }  
  •         }  
  •         return instance;  
  •     }  
  • }

4,

  • class S4 {  
  •     private S4() {  
  •         System.out.println("ok4");  
  •     }  
  •  
  •     privatestaticclass S4Holder {  
  •         static S4 instance = new S4();  
  •     }  
  •  
  •  
  •     publicstatic S4 getInstance() {  
  •         return S4Holder.instance;  
  •     }  
  • }

以上内容均引自与博客:http://blog.csdn.net/it_man/article/details/5787567,里面还详尽的介绍了单例模式。。不过以我的理解,作者是认为双重检测在java中是不能成立的。。不知道当时面试官为何这么说。。难道他是c语言出身么?

 

posted on 2012-08-23 15:07  Seving  阅读(248)  评论(0编辑  收藏  举报

导航