RefactoringGuru/design-patterns-csharp

Making Singleton a 'sealed' class

121yaseen opened this issue · 3 comments

Hi,
First of all, thank you for writing "Dive into Design Patterns" and making it public through "refactoring. guru". I am a fresher and if there wasn't refactoring. guru and its cool illustrations, Design Patterns would be another topic that I have just a "vague" idea. While learning I noticed a difference in the C# implementation of Singleton Pattern, the singleton class wasn't sealed.

Why 'sealed' keyword?

  • Sealed restricts class inheritance
  • Even if sealed was not there, since the constructor is private, we cannot create a derived class from the singleton class. But we can make a nested class (a new class inside the singleton class) derived from the singleton class. We can create the objects of the child class and by that, we could create multiple instances of the singleton class. This violates the principles of the singleton design pattern.
  • By making a singleton class a sealed class, we cannot derive a class from it and will restrict the possibility of violating the principles of a singleton class. ie, sealed keyword prevents any inheritance even in the nested classes.
  • In short, the private constructor will restrict any external instantiation of objects and sealed will prevent the class inheritance.

References :
https://csharpindepth.com/articles/singleton
https://en.wikipedia.org/wiki/Singleton_pattern#C#
https://www.youtube.com/watch?v=LypTOnfkfvA

Hi!

Thanks for your suggestion. Would you mind sending a pull request for this change?

Already linked one. Implemented only for Non Thread Safe.