Java单例模式的写法

https://www.cnblogs.com/dongyu666/p/6971783.html

1、volatile 写法(优点高效且线程安全,缺点不够优雅、简洁)

public class Single4 {
    private static volatile Single4 instance;
    private Single4() {}
    public static Single4 getInstance() {
        if (instance == null) {
            synchronized (Single4.class) {
                if (instance == null) {
                    instance = new Single4();
                }
            }
        }
        return instance;
    }
}

2、静态内部类写法,《Effective Java》推荐(吊)

public class Singleton {
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

    private Singleton (){}
    public static final Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

3、枚举写法《Effective Java》第二版推荐(极吊)

public enum SingleInstance {

    INSTANCE;

    public void fun1() { 
        // do something
    }
}

 

// 使用

SingleInstance.INSTANCE.fun1();

猜你喜欢

转载自blog.csdn.net/Dopamy_BusyMonkey/article/details/86574523