手记

设计模式-单例模式

1.懒汉式-线程不安全

public class SingletonLazyNoSafe {    private static SingletonLazyNoSafe singletonLazyNoSafe;    private SingletonLazyNoSafe() {}    public static SingletonLazyNoSafe getInstance(){        if (singletonLazyNoSafe ==null){
            singletonLazyNoSafe = new SingletonLazyNoSafe();
        }        return singletonLazyNoSafe;
    }
}

2.懒汉式-线程安全

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

3.饿汉式-线程安全

public class SingletonHungerSafe {
    private static SingletonHungerSafe singletonHungerSafe = new SingletonHungerSafe();    private SingletonHungerSafe(){}    public static SingletonHungerSafe getInstance(){        return singletonHungerSafe;
    }
}

4.饿汉式-静态代码块-线程安全

public class SingletonHungerStaticBlockSafe {
    private static SingletonHungerStaticBlockSafe singletonHungerStaticBlockSafe;    static {
        singletonHungerStaticBlockSafe = new SingletonHungerStaticBlockSafe();
    }    private SingletonHungerStaticBlockSafe(){}    public static SingletonHungerStaticBlockSafe getInstance(){        return singletonHungerStaticBlockSafe;
    }
}

5.懒汉式-静态内部类-线程安全

public class SingletonStaticInnerClass {    private SingletonStaticInnerClass(){}    private static class InstanceSingleton{        public static final SingletonStaticInnerClass SINGLETON_STATIC_INNER_CLASS = new SingletonStaticInnerClass();
    }    public static SingletonStaticInnerClass getInstance(){        return InstanceSingleton.SINGLETON_STATIC_INNER_CLASS;
    }
}

6.懒汉式-双重校验锁-线程安全

public class SingletonDoubleVerifyLock {    private static SingletonDoubleVerifyLock singletonDoubleVerifyLock;    private SingletonDoubleVerifyLock(){}    public static SingletonDoubleVerifyLock getInstance(){        if (singletonDoubleVerifyLock == null){            synchronized (SingletonDoubleVerifyLock.class){                if (singletonDoubleVerifyLock == null){
                    singletonDoubleVerifyLock = new SingletonDoubleVerifyLock();
                }
            }
        }        return singletonDoubleVerifyLock;
    }
}

7.懒汉式-枚举实现-线程安全(推荐)

public enum SingletonEnum {
    INSTANCE;
    SingletonEnum() {}
}



作者:李帅超
链接:https://www.jianshu.com/p/ea1ad96255b7


0人推荐
随时随地看视频
慕课网APP