单例模式

2017-04-19  本文已影响0人  Hong2018

单例<件>模式

1.急切实例化 <饿汉>

public class Singleton {
    
    private static Singleton uniqueInstance = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        
        return uniqueInstance;
    }
}

2.同步getInstance()方法

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

        return uniqueInstance;
    }
}

3.双重检查枷锁 <性能比同步getInstance()好, 需要JDK Java5或以上>

public class Singleton {
    
    private volatile static Singleton uniqueInstance;

    private Singleton() {}

    public static Singleton getInstance() {

        if (uniqueInstance == null) {
            
            synchronized (Singleton.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new Singleton();
                }
            }

        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读