设计模式(5)单例模式

模式介绍

单例模式是一种创建型设计模式,其中一个类只保证只有一个实例,该实例可以全局访问。

这意味着该模式强制特定对象不具有可访问的构造函数,并且对该对象执行的任何访问都是在该对象的同一实例上执行的。

示例

我们模拟一下餐馆里用于通知上菜铃铛,它在柜台上只有一个。

下面代码中syncRoot是为了线程安全。

/// <summary>
/// Singleton
/// </summary>
public sealed class TheBell
{
    private static TheBell bellConnection;
    private static object syncRoot = new Object();
    private TheBell()
    {

    }

    /// <summary>
    /// We implement this method to ensure thread safety for our singleton.
    /// </summary>
    public static TheBell Instance
    {
        get
        {
            lock(syncRoot)
            {
                if(bellConnection == null)
                {
                    bellConnection = new TheBell();
                }
            }

            return bellConnection;
        }
    }

    public void Ring()
    {
        Console.WriteLine("Ding! Order up!");
    }
}

总结

单例模式的对象只能是一个实例。它不是全局变量,许多人认为它们违反了软件设计的原则,但它确实有其用途,因此应谨慎使用。

源代码

https://github.com/exceptionnotfound/DesignPatterns/tree/master/Singleton

原文

https://www.exceptionnotfound.net/singleton-the-daily-design-pattern/

原文地址:https://www.cnblogs.com/talentzemin/p/9822125.html