单例模式:
关键点: 1、一个类只有一个实例; 2、类自行创建该实例; 3、类自行向整个系统提供该实例。
代码展示:
namespace SingleTon { /// <summary> /// 懒汉单例、多线程安全 /// 比较懒,在类加载时,不创建实例,因此类加载速度快,但运行时获取对象的速度慢 /// </summary> public class LazySingleTon { private static LazySingleTon instance = null; //多线程安全 private static object lockObject = new object(); private LazySingleTon() { Console.WriteLine("private LazySingleTon()"); } public static LazySingleTon Instance { get { //不必每次锁,提高效率 if (instance == null) { //多线程安全 lock (lockObject) { if (instance == null) { return new LazySingleTon(); } } } return instance; } } } /// <summary> /// 饿汉单例 /// 在类加载时就完成了初始化,所以类加载较慢,但获取对象的速度快 /// </summary> public class EagerSingleTon { // readonly 分配的动态内存 private static readonly EagerSingleTon instance = new EagerSingleTon(); private EagerSingleTon() { Console.WriteLine("private EagerSingleTon()"); } public static EagerSingleTon Instance { get { return instance; } } } class Program { static void Main(string[] args) { var lazy = LazySingleTon.Instance; var eager = EagerSingleTon.Instance; } } }
原文地址:https://www.cnblogs.com/uicodeintoworld/p/8986785.html
时间: 2024-10-18 07:49:14