Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

C#에서 싱글톤 클래스가 항상 봉인된 이유는 무엇입니까?

<시간/>

Sealed 키워드는 클래스를 상속할 수 없음을 의미합니다. 생성자를 private로 선언하면 클래스의 인스턴스를 생성할 수 없습니다.

개인 생성자가 있는 기본 클래스를 가질 수 있지만 여전히 해당 기본 클래스에서 상속하고 일부 공용 생성자를 정의하고 해당 기본 클래스를 효과적으로 인스턴스화합니다.

생성자는 상속되지 않으며(따라서 파생 클래스에는 기본 클래스가 있기 때문에 모든 private 생성자가 없습니다) 해당 파생 클래스는 항상 기본 클래스 생성자를 먼저 호출합니다.

클래스를 봉인으로 표시하면 누군가가 클래스에서 상속을 받지 못하도록 하기 때문에 신중하게 구성된 싱글톤 클래스에서 다른 사람이 사소하게 작업하는 것을 방지할 수 있습니다.

예시

static class Program {
   static void Main(string[] args){
      Singleton fromStudent = Singleton.GetInstance;
      fromStudent.PrintDetails("From Student");

      Singleton fromEmployee = Singleton.GetInstance;
      fromEmployee.PrintDetails("From Employee");

      Console.WriteLine("-------------------------------------");

      Singleton.DerivedSingleton derivedObj = new Singleton.DerivedSingleton();
      derivedObj.PrintDetails("From Derived");
      Console.ReadLine();
   }
}
public class Singleton {
   private static int counter = 0;
   private static object obj = new object();

   private Singleton() {
      counter++;
      Console.WriteLine("Counter Value " + counter.ToString());
   }
   private static Singleton instance = null;

   public static Singleton GetInstance{
      get {
         if (instance == null)
            instance = new Singleton();
         return instance;
      }
   }

   public void PrintDetails(string message){
      Console.WriteLine(message);
   }

   public class DerivedSingleton : Singleton {
   }
}