{C#}设计模式辨析.单例
作者:
码农猫爸 | 来源:发表于
2021-08-05 07:57 被阅读0次背景
示例
using System;
using static System.Console;
namespace DesignPattern_Singleton
{
public class Singleton
{
// 私有构造器,禁止类外实例化
private Singleton() { }
// 共用实例必须静态
public static Singleton Instance = Lazy.Value;
// 懒对象:延迟到首次调用时生成,且多线程安全
private static Lazy<Singleton> Lazy
=> new Lazy<Singleton>(() => new Singleton());
public void Print()
=> WriteLine("The printer is printing...");
}
class Demo
{
static void Main(string[] args)
{
var printer1 = Singleton.Instance;
var printer2 = Singleton.Instance;
WriteLine($"The printers are {(printer1 == printer2 ? "same" : "different")}.");
printer1.Print();
ReadKey();
}
}
}
本文标题:{C#}设计模式辨析.单例
本文链接:https://www.haomeiwen.com/subject/bggmvltx.html
网友评论