欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

单例模式的各种姿势

程序员文章站 2022-07-13 23:39:26
...

饿汉式:

基于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() {         }  
}