继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

设计模式-单例模式

慕神8447489
关注TA
已关注
手记 1273
粉丝 174
获赞 956

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


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP