java单例模式Singleton的设计

常用版本

public class Singleton {
    private static Singleton singleton = null;
    private Singleton() {  }
    public static Singleton getInstance() {
        if (singleton== null) {
            singleton= new Singleton();
        }
        return singleton;
    }
}

实际版本

public class Singleton { 
      private static Singleton instance; 
      private Singleton (){}
      public static synchronized Singleton getInstance() { 
      if (instance == null) { 
          instance = new Singleton(); 
      } 
      return instance; 
}

多线程安全高效版本

public class Singleton
{
    private volatile static Singleton singleton = null;
    private Singleton()  {    }
    public static Singleton getInstance()   {
        if (singleton== null)  {
            synchronized (Singleton.class) {
                if (singleton== null)  {
                    singleton= new Singleton();
                }
            }
        }
        return singleton;
    }
}

如果Singleton是需要序列化,那么我们可以通过序列化接口的readResolve方法控制别人多次反序列化

public class Singleton implements Serializable
{
    ......
    ......
    protected Object readResolve()
    {
        return getInstance();
    }
}


http://www.runoob.com/design-pattern/singleton-pattern.html

http://coolshell.cn/articles/265.html

http://www.blogjava.net/kenzhh/archive/2013/03/15/357824.html

http://wuchong.me/blog/2014/08/28/how-to-correctly-write-singleton-pattern/

猜你喜欢

转载自yys19781104.iteye.com/blog/2259205
今日推荐