美文网首页
【设计模式】单例模式

【设计模式】单例模式

作者: WilsonPan | 来源:发表于2020-05-02 01:29 被阅读0次

定义

确保某个类只有一个实例

实现方式

饿汉式加载(线程安全)

public sealed class Singleton
{
    private static Singleton _instance = new Singleton();
    //将构造函数设置私有,外部不能new
    private Singleton() { }
    public static Singleton Instance => _instance;
}

等价于

public sealed class Singleton
{
    private static Singleton _instance;
    static Singleton()
    {
        _instance = new Singleton();
    }
    //将构造函数设置私有,外部不能new 
    private Singleton() { }
    public static Singleton Instance => _instance;
}

懒汉式加载

  • 非线程安全
public sealed class Singleton
{
    private static Singleton _instance;
    private Singleton() { }
    public static Singleton Instance => _instance = _instance ?? new Singleton();
}
  • 线程安全
  1. Double Check
public sealed class Singleton
{
    private static readonly object _lock = new object();
    private static Singleton _instance;
    private Singleton()
    {
        Console.WriteLine("Singleton Constructor");
    }
    public static Singleton Instance
    {
        get
        {
            /// 避免走内核代码
            if (_instance != null) return _instance;

            lock (_lock)
            {
                if (_instance == null)
                {
                    var temp = new Singleton();
                    //确保_instance写入之前,Singleton已经初始化完成
                    System.Threading.Volatile.Write<Singleton>(ref _instance, temp);
                }
            }
            return _instance;
        }
    }
}
  1. 借助Lazy
public sealed class Singleton
{
    private static Lazy<Singleton> _instance = new Lazy<Singleton>(() => new Singleton(), true);
    private Singleton()
    {
        Console.WriteLine("Singleton Constructor");
    }
    public static Singleton Instance => _instance.Value;
}

示例代码 - github

相关文章

  • 单例模式Java篇

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

  • python中OOP的单例

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

  • 单例

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

  • 设计模式 - 单例模式

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

  • 设计模式

    常用的设计模式有,单例设计模式、观察者设计模式、工厂设计模式、装饰设计模式、代理设计模式,模板设计模式等等。 单例...

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

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

  • python 单例

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

  • 基础设计模式:单例模式+工厂模式+注册树模式

    基础设计模式:单例模式+工厂模式+注册树模式 单例模式: 通过提供自身共享实例的访问,单例设计模式用于限制特定对象...

  • 单例模式

    JAVA设计模式之单例模式 十种常用的设计模式 概念: java中单例模式是一种常见的设计模式,单例模式的写法...

  • 设计模式之单例模式

    单例设计模式全解析 在学习设计模式时,单例设计模式应该是学习的第一个设计模式,单例设计模式也是“公认”最简单的设计...

网友评论

      本文标题:【设计模式】单例模式

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