前言
单例模式:程序运行时只创建一个对象实例。
运行结果
代码
// 单例模式
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();}
}