单例模式的各种姿势

xiaoxiao2021-02-27  378

饿汉式:

基于classloder机制避免了多线程的同步问题,不过,instance在类装载时就实例化

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

懒汉式:

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

双检锁

volatile关键字不能丢

public class Singleton { private volatile static Singleton instance = new Singleton(); private static Object synObject = new Object(); private Singleton(){} public static Singleton getInstance() { if (instance!=null) { return instance; } synchronized(synObject) { if (instance==null) { instance = new Singleton(); } } return instance; } public void executeMethod(...) { ... } }

静态内部类

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

枚举类

JDK1.5中才加入enum特性。不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象,

public enum Singleton { INSTANCE; public void whateverMethod() { } }
转载请注明原文地址: https://www.6miu.com/read-2249.html

最新回复(0)