自学内容网 自学内容网

【C#设计模式(1)——单例模式】简单版

前言

单例模式:程序运行时只创建一个对象实例。

运行结果

在这里插入图片描述

代码

// 单例模式
public class SingleInstance
{
    #region 
    private static SingleInstance instance;
    public static SingleInstance GetInstance(string name, string value)
    {
        if (instance == null)
        {
            instance = new SingleInstance(name,value);
        }
        return instance;
    }
    private SingleInstance(string name ,string value)
    {
        this._name = name;
        this._value = value;
    }
    #endregion 

    private string _name;
    private string _value;

    public string GetName { get => _name; }
    public string GetValue { get => _value; }

    public void Print()
    {
        Console.WriteLine($"you name is{_name},value = {_value}");
    }
}
// 单例模式-线程安全
public class SingletonThreadSafe
{
    private static SingletonThreadSafe instance;
    private static object _lock = new object();
    public static SingletonThreadSafe GetInstance()
    {
        if( instance == null )
        {
            lock ( _lock )
            {
                if (instance==null)
                {
                    instance = new SingletonThreadSafe();
                }
            }
        }
        return instance;
    }
    public void Print( string message )
    {
        Console.WriteLine($"thread safe singleton instance: message =  {message}");
    }

///---------------------------------------------------
internal class Program
{
    static void Main(string[] args)
    {
        SingleInstance single = SingleInstance.GetInstance("单例模式","只创建一个实例");
        single.Print();
        SingletonThreadSafe.GetInstance().Print($"{single.GetValue}{single.GetName}");
        Console.ReadLine();
        Console.ReadKey();
    }
}

原文地址:https://blog.csdn.net/weixin_43626218/article/details/143647016

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!