美文网首页
单例设计模式笔记

单例设计模式笔记

作者: NC丶脑补东 | 来源:发表于2020-07-17 22:31 被阅读0次

记录几种单例模式写法。

饿汉模式(线程不安全)

    /**
     * 饿汉模式(线程不安全)
     * @return
     */
    private static Singleton getInstanceHungry() {
        mInstance = new Singleton();
        return mInstance;
    }

懒汉模式(线程不安全)

     /**
     * 懒汉模式(线程不安全)
     * @return
     */
    private static Singleton getInstanceLazy() {
        if (mInstance == null) {
            mInstance = new Singleton();
        }
        return mInstance;
    }

懒汉锁模式(线程安全)

    /**
     * 懒汉锁模式(线程安全)
     *
     * @return
     */
    private synchronized static Singleton getInstanceLazyThreadSafetyOne() {
        if (mInstance == null) {
            mInstance = new Singleton();
        }
        return mInstance;
    }

懒汉双重判断模式(线程安全)

    /**
     * volatile 修饰作用
     * 1.防止重排序
     * 2.值改变通知其他线程可见
     */
    private static volatile Singleton mInstance;

    /**
     * 懒汉双重判断模式(线程安全)
     *
     * @return
     */
    private synchronized static Singleton getInstanceLazyThreadSafetyTwo() {
        if (mInstance == null) {
            synchronized (Singleton.class) {
                if (mInstance == null) {
                    mInstance = new Singleton();
                }
            }
        }
        return mInstance;
    }

静态内部类模式

    /**
     * 静态内部类模式
     */
    public static class SingletonHolder {
        private static volatile Singleton mInstance;
    }

    public static Singleton getInstanceInnerclass() {
        return SingletonHolder.mInstance = new Singleton();
    }

容器管理模式

    /**
     * 容器管理模式
     */

    private static Map<String, Object> mSingleMap = new HashMap<>();


    static {
        mSingleMap.put("activity_manager", new Singleton());
    }

    public static Object getService(String serviceName) {
        return mSingleMap.get(serviceName);
    }

注:定义 private static volatile Singleton mInstance 带有 volatile 修饰主要是为了保证线程可见性和防止代码重排序的问题。

相关文章

  • 【Java】设计模式 —— 深入浅出单例模式

    学习笔记 参考:深入浅出单实例SINGLETON设计模式单例模式【Java】设计模式:深入理解单例模式 场景:一般...

  • 单例模式Java篇

    单例设计模式- 饿汉式 单例设计模式 - 懒汉式 单例设计模式 - 懒汉式 - 多线程并发 单例设计模式 - 懒汉...

  • python中OOP的单例

    目录 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • 单例

    目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • python 单例

    仅用学习参考 目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计...

  • 2018-04-08php实战设计模式

    一、单例模式 单例模式是最经典的设计模式之一,到底什么是单例?单例模式适用场景是什么?单例模式如何设计?php中单...

  • 设计模式第二篇、单例设计模式

    目录1、什么是单例设计模式2、单例设计模式的简单实现3、单例设计模式面临的两个问题及其完整实现4、单例设计模式的应...

  • 设计模式 - 单例模式

    设计模式 - 单例模式 什么是单例模式 单例模式属于创建型模式,是设计模式中比较简单的模式。在单例模式中,单一的类...

  • 设计模式系列—单例(Singleton Pattern)模式

    《Head First设计模式》读书笔记 单例模式 一,背景介绍 1,为什么要使用单例模式? 在实际的开发中我们有...

  • 设计模式整理(2) 单例模式

    学习《Android 源码设计模式解析与实践》系列笔记 什么是单例 单例模式是应用最广,也是最容易理解的模式之一。...

网友评论

      本文标题:单例设计模式笔记

      本文链接:https://www.haomeiwen.com/subject/kxmnhktx.html