设计模式之单例设计模式

/**
 * 单例设计模式
 * 特点:全局只有一个对象;对应由单例类提供,单例类构造方法私有;单例类对外提供一个静态方法访问对象。
 * 选择场景:
 * 单线程使用 使用SingletonPattern
 * 多线程使用 饿汉模式 SafeThredSingleton
 * 多线程性能要求 MutiThreadSingleton 或者 InnerSingleton
 */
public class SingletonPattern {
    private static SingletonPattern singletonPattern = null;

    private SingletonPattern() {
    }

    /**
     * 懒汉式获取单列对象
     * 会有线程安全问题
     */
    public static synchronized SingletonPattern getSingleton() {
        if (singletonPattern == null) {
            return new SingletonPattern();
        }
        return singletonPattern;
    }

    /**
     * 线程安全 饿汉模式
     */
    static class SafeThredSingleton {
        private static SafeThredSingleton safeThredSingleton = new SafeThredSingleton();

        private SafeThredSingleton() {
        }

        public static SafeThredSingleton getSafeThredSingleton() {
            return safeThredSingleton;
        }
    }

    /**
     * 多线程性能最优,会存在指令重拍还是有问题的
     */
    static class MutiThreadSingleton {
        private static volatile MutiThreadSingleton mutiThreadSingleton = null;

        private MutiThreadSingleton() {
        }

        public static MutiThreadSingleton getInstance() {
            if (mutiThreadSingleton == null) {
                synchronized (MutiThreadSingleton.class) {
                    if (mutiThreadSingleton == null) {
                        mutiThreadSingleton = new MutiThreadSingleton();
                    }
                }

            }
            return mutiThreadSingleton;
        }
    }

    /**
     * 基于静态内部类
     */

    static class InnerSingleton {
        private InnerSingleton() {
        }

        ;

        private static class InnerClass {
            private static final InnerSingleton innerSingleton = new InnerSingleton();
        }

        public static InnerSingleton getInstance() {
            return InnerClass.innerSingleton;
        }
    }

}
 

参考:https://www.liangzl.com/get-article-detail-122498.html

https://blog.csdn.net/chutian6666/article/details/77282332

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值