Why should the singleton class be sealed?

I want to know why the singleton class should be sealed. If we give the constructor as a quotient, can we prevent the class from outputting correctly? .. Below I insert a few lines from MSDN. Please give me the color on it.

In this strategy, an instance is created the first time you call any member of the class. The general language runtime takes care of variable initialization. The class is marked sealed to prevent output that might add instances . For a discussion of the pros and cons of class labels, see [Sells03]. In addition, the variable is marked readonly, which means that it can only be assigned during static initialization (which is shown here) or in the class constructor.

http://msdn.microsoft.com/en-us/library/ff650316.aspx

+6
source share
4 answers

If we give the constructor as private, can we prevent the class from being output correctly?

Not really:

public class NotReallySingleton { private NotReallySingleton() {} public class CursesFoiledAgain : NotReallySingleton { } } ... NotReallySingleton x = new CursesFoiledAgain(); NotReallySingleton y = new CursesFoiledAgain(); 

This works because private access is limited to type program text, including nested types. Thus, CursesFoiledAgain has access to the private NotReallySingleton constructor.

But even leaving this aside, if your intention is that no one can learn from the class, why don't you want to communicate this intention as clearly as possible through sealed ?

+10
source

The sealed means that a class cannot be inherited. Declaring private constructors means that instances of the class cannot be created.

This is not the same thing. You can have a base class with a private constructor, but still inherit from this base class, define some public constructors, and efficiently create this base class.

Remember that constructors are not inherited (therefore, a derived class will not have all private constructors just because the base class does this), and these derived classes always invoke base class constructors. Labeling a sealed class prevents someone from trivially working around your carefully designed singleton class, because it keeps someone from inheriting from the class.

+2
source

The private constructor in C # will only help us prevent any external instances of the class, and the sealed keyword will prevent class inheritance. Suppose you have a nested class, and if you did not declare the class as private, then you can create an instance of the class. Take a look at this article .

+1
source

These are some kind of design guidelines that you obviously can follow or not. This simply indicates your design intent, as in the case of the base class designating it as abstract , to avoid any possible mess in the future.

0
source

Source: https://habr.com/ru/post/921394/


All Articles