Detailed description of private and protected Constructor
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.
The Code is as follows: (new classb is also indirectly new classa)
Public class classa
{
Protected classa ()
{
}
}
Public class classb: classa
{
Public classb ()
{
}
}
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 class classa
{
Private classa ()
{
}
}
Public class classb: classa
{
Public classb ()
{
}
}
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 class classa
{
Protected classa ()
{
}
Public classa create ()
{
// Here you can perform special operations, such as assigning an initial value to the classa attribute or writing some logs. What do you like to do?
Return new classa ();
}
}