标签:
1、饿汉式:
/** * 缺点:没有达到lazy loading的效果 */ public class Singleton { private static Singleton instance = new Singleton(); private Singleton() { } public static Singleton getInstance() { return instance; } }
2、懒汉式:
class Singleton { private static Singleton instance = null; private Singleton() { } public static synchronized Singleton getInstance() { if (instance == null) instance = new Singleton(); return instance; } }
3、双重校验锁:
/** *双重校验锁,在当前的内存模型中无效 */ class Singleton { private static Singleton instance = null; private Singleton() { } public static synchronized Singleton getInstance() { if (instance == null) synchronized (Singleton.class) { if (instance == null) instance = new Singleton(); } return instance; } }
4、静态内部类:
/** * 优点:加载时不会初始化静态变量instance ,因为没有主动使用,达到Lazy loading */ class Singleton { private static class SingletonHolder { private final static Singleton instance = new Singleton(); } private Singleton() { } public static Singleton getInstance() { return SingletonHolder.instance; } }
5、枚举:
/** * Effective Java》作者推荐使用的方法,优点:不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象 */ enum EnumSingleton{ instance; public void doSomeThing(){ } }
标签:
原文地址:http://my.oschina.net/u/2350638/blog/499040