首页 > 代码库 > 单例模式

单例模式

参考:http://my.oschina.net/suyewanwan/blog/102525

1.懒汉式:

public class Singleton {    private static Singleton singleton;    private Singleton() {}  //此类不能被实例化    public static synchronized Singleton getInstance() {        if (singleton == null) {            singleton = new Singleton();        }        return singleton;    }}


2.饿汉式:
public class Singleton {    private static final Singleton SINGLETON = new Singleton();    private Singleton() {}  //此类不能被实例化    public static Singleton getInstance() {        return SINGLETON;    }}


3.内部类单例模式:
public class Singleton {    private Singleton() {} //构造方法是私有的,从而避免外界利用构造方法直接创建任意多实例。    public static Singleton getInstance() {        return Holder.SINGLETON;    }    private static class Holder {       private static final Singleton SINGLETON = new Singleton();    }}

单例模式