如何在 C# 中实现单例设计模式?

csharpserver side programmingprogramming更新于 2025/4/20 11:07:17

单例模式属于创建型模式

当我们需要确保某个类只有一个对象被实例化时,可以使用单例设计模式。创建的这个实例负责协调整个应用程序的操作。

作为实现指南的一部分,我们需要通过将类的所有构造函数声明为私有来确保该类只有一个实例存在。此外,为了控制单例访问,我们需要提供一个返回对象单个实例的静态属性。

示例

Sealed 确保类被继承,并且对象实例化在派生类中受到限制

使用 null 初始化的私有属性

确保仅创建对象的一个​​实例

基于 null 条件

私有构造函数确保对象不会在类本身以外的其他地方被实例化

可通过单例实例调用的公共方法

public sealed class Singleton {
   private static int counter = 0;
   private static Singleton instance = null;
   public static Singleton GetInstance {
      get {
         if (instance == null)
         instance = new Singleton();
         return instance;
      }
   }
   private Singleton() {
      counter++;
      Console.WriteLine("Counter Value " + counter.ToString());
   }
   public void PrintDetails(string message) {
      Console.WriteLine(message);
   }
}
class Program {
   static void Main() {
      Singleton fromFacebook = Singleton.GetInstance;
      fromFacebook.PrintDetails("From Facebook");
      Singleton fromTwitter = Singleton.GetInstance;
      fromTwitter.PrintDetails("From Twitter");
      Console.ReadLine();
   }
}

输出

Counter Value 1
From Facebook
From Twitter

相关文章