首页 > 代码库 > [设计模式] 单例设计模式

[设计模式] 单例设计模式

1.懒汉式(内部类式)

  

/** * Created by pmx on 14-9-14. */public class Singleton {
private Singleton() {} public static Singleton getInstance() { return SingletonHolder.instance; } static class SingletonHolder { private static Singleton instance = new Singleton(); }}

 

2.懒汉式(同步)

/** * Created by pmx on 14-9-14. */public class Singleton {    private static Singleton singleton = null;    private Singleton() {}    public static Singleton getInstance() {        if (singleton == null)        {            synchronized (Singleton.class)            {                if (singleton == null)                    singleton = new Singleton();            }        }        return singleton;    }}

 

[设计模式] 单例设计模式