设计模式--单例模式

来源:互联网 发布:传经破解软件 编辑:程序博客网 时间:2024/05/16 01:36
原文地址http://xiaotao-2010.iteye.com/blog/1175153

    1、饿汉单例 

JVM运行时则加载该单例(最常用),不用考虑线程安全等问题 

public class HungrySingleton {  public class EagerSingleton {     private static final EagerSingleton eagerSingleton = new EagerSingleton();     private EagerSingleton(){    }     public static EagerSingleton getInstance() {            return eagerSingleton;     } }

 2、懒汉单例 
程序使用到的时候加载,本程序中需要考虑线程安全问题,所以加入的synchronized (锁)机制,同时采用了DCL验证机制。 

public class Singleton { // 懒汉式单例         private static Singleton singleton = null;         private Singleton() {       }         public static Singleton getInstance() {      //Double-Check Locking 保证线程安全        if (singleton == null) {               synchronized (Singleton.class) {                               if(singleton == null) {                   singleton = new Singleton();                                }               }           }           return singleton;       }   }  

  3、内部类实现单例 (可以使用在面试时show技术方面) 
参考:Spring in action 2nd 中的实例 
样确保线程安全的同时, 比上面创建静态实例域的办法还有一个好处就是:  
SingletonHolder中可以使用静态方法替换静态域, 实现比较复杂的逻辑, 而不仅仅是new Singleton()这样简单地调用构造方法. 

public class Singleton {    private Singleton() {}    private static class SingletonHolder {        static Singleton instance = new Singleton();    }    public static Singleton getInstance() {        return SingletonHolder.instance;    }}


0 0
原创粉丝点击