Why are singleton classes in C# always sealed?

王林
Release: 2023-08-29 08:21:05
forward
636 people have browsed it

为什么 C# 中的单例类总是密封的?

sealed keyword means that the class cannot be inherited. Declaring the constructor as private means that no instance of the class can be created.

You can have a base class with a private constructor but still inherit from that base class, define some public constructors, and effectively instantiate the base class.

Constructors is not inherited (so the derived class won't just because the base class has all private constructors), and the derived class always calls the base class constructor first.

Marking a class as sealed prevents someone from working around your carefully constructed singleton class because it prevents someone from inheriting from the class.

Example

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 {
   }
}
Copy after login

The above is the detailed content of Why are singleton classes in C# always sealed?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template