When implementing the singleton mode, you often need to mark the constructor as private and protected to prevent external entities from directly constructing a new instance through the new operator.
As we all know, the main difference between private and protected is that the latter allows subclass to call Methods marked as protected.
Another common sense: In the process of constructing a subclass using the new operator,. NET will first construct a parent class, so that recursion will continue until the object
That is to say, when it is marked as protected, it is actually possible to indirectly construct the parent class object through inheritance.
CodeAs follows: (New classb is also indirectly new classa)
Public ClassClassa
{
ProtectedClassa ()
{
}
}
Public ClassClassb: classa
{
PublicClassb ()
{
}
}
Private,! When it is marked as private, it means that no type can inherit private.
Of course, you can write the following code: (but the editor will tell you that 'classa. classa () 'is inaccessible due to its protection level)
Public ClassClassa
{
PrivateClassa ()
{
}
}
Public ClassClassb: classa
{
PublicClassb ()
{
}
}
The reason is that you cannot call the classa constructor when constructing classb.
From the perspective of development, if a class is not expected to be inherited or cannot be inherited, it should be marked as sealed to prevent others from accidentally inheriting the class, the classa here should be marked as sealed
Therefore, for the singleton mode private, it is a good choice to seal the class and protected it is also a usable implementation.
Sometimes, the constructor does not want to use the singleton mode, but also wants to regulate the behavior of the caller through this method.
The Code is as follows:
Public ClassClassa
{
ProtectedClassa ()
{
}
PublicClassa create ()
{
//Special operations can be performed here, such as assigning an initial value to the classa attribute or writing some logs. What do you like to do?
Return NewClassa ();
}
}
At this time, I personally suggest using the protected constructor, because it will not deprive the inherited ability.
This capability is required in my "A project needs to call more than 100 existing DLL" project. The classa created through create is actually a subclass of classa, A special handling is made.
The system. net. webrequest. Create method in. NET is as follows:
PS: The problem with private constructor is that it indirectly denies the possibility of being inherited. If this is the case, it is recommended to mark the type as sealed
PS: if you do not want to deprive the inherited capabilities, use protected.