陈巧倩

设计模式-单例模式

· 254 words · 2 minutes to read
Categories: CSharp
Tags: Design Pattern

Singleton单例模式属于创建型设计模式,确保一个类只有一个实例,并提供该实例的全局访问点。

Design Pattern:Singleton 🔗

基本介绍 🔗

构成 🔗

  • 密封类
  • 私有和无参的单一构造函数
  • 获取实例引用的静态和开放方法

优点 🔗

  • 单例模式可以实现接口
  • 可以实现延迟加载并且可以使用静态初始化
  • 规范依赖关系
  • 单点访问,易于维护

缺点 🔗

  • 不能继承,与单一职责原则冲突
  • 降低了并行执行的可能性

实现 🔗

C#中有多种实现单例设计模式的方法

无线程安全的单例 🔗

public sealed class Singleton
{
    private static Singleton _instance = null;
    private Singleton()
    {
    }
    public static Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new Singleton();
            }
            return _instance;
        }
    }
}

解释

  • 多线程情况下不安全,多线程中会触发多次if (instance == null)为真,构造多份实例,违背单一构造原则。

使用锁的线程安全单例 🔗

public sealed class Singleton
{
    private static Singleton _instance = null;
    private static readonly object _lock = new object();

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            lock (_lock)
            {
                if (_instance == null)
                {
                    _instance = new Singleton();
                }
                return _instance;
            }
        }
    }
}

解释

  • 线程安全,使用锁来确保只创建一个实例。
  • 性能受影响,每次请求实例都需要获取锁。

使用双重检查锁定实现线程安全单例 🔗

public sealed class Singleton
{
    private static Singleton _instance = null;
    private static readonly object _lock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new Singleton();
                    }
                }
            }
            return _instance;
        }
    }
}

解释

  • 依然存在性能问题。

无锁线程安全函数单例 🔗

public sealed class Singleton
{
    private static readonly Singleton _instance = new Singleton();
    
    static Singleton()
    {
    }
    
    private Singleton()
    {
    }
    public static Singleton Instance
    {
        get
        {
            return _instance;
        }
    }
}

解释

  • 静态构造函数用于初始化任何静态数据,或执行仅需执行一次的特定操作。 将在创建第一个实例或引用任何静态成员之前自动调用静态构造函数。 静态构造函数最多调用一次。当类型有BeforeFieldInit标志时指定调用此类型的静态方法并不强制系统初始化此类型。
  • 实例创建,需要对实例以外的静态成员的引用。

Lazy 泛型类在单例 🔗

public sealed class Singleton
{
    private static readonly Lazy<Singleton> _instance = new Lazy<Singleton>(() => new Singleton());

    public static Singleton Instance { get { return _instance.Value; } }

    private Singleton()
    {
    }
}

解释

  • .NET 4或更高版本。
  • Lazy 类提供从多个线程进行访问的延迟初始化。

结论 🔗

搬砖愉快!