单例模式

单例模式的写法

//饿汉(线程不安全,不正确)
class Singleton1 {
    private static Singleton1 instance = new Singleton1();
    private Singleton1(){
    }
    public static Singleton1 getInstance(){         
        return instance;
    }
}
//饱汉(线程安全但是高并发性能不高)
class Singleton2 {
    private static Singleton2 instance;
    private Singleton2(){
        
    }
    public static synchronized Singleton2 getSingleton2(){
        if(instance == null){
            instance = new Singleton2();
        }
        return instance;
    }
}
//线程安全,性能又高,写法常见
class Singleton3{
    private static Singleton3 instance;
    private static byte[] lock = new byte[0];
    private Singleton3(){
        
    }
    public static Singleton3 getInstance() {
        if(instance == null){
            synchronized (lock) {
                if(instance == null){
                    instance = new Singleton3();
                }
            }
        }
        return instance;
    }
}
//线程安全,性能又高的另一种,也很常见
class Singleton4 {
    private static Singleton4 instance;
    private static ReentrantLock lock = new ReentrantLock();
    private Singleton4 () {
        
    }
    public static Singleton4 getInstance() {
        if(instance == null){
            lock.lock();
            if(instance == null){
                instance == new Singleton4();
            }
            lock.unlock();
        }
        return instance;
    }
}

你可能感兴趣的:(单例模式)