【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();
}
}