Singleton mode and monostate mode both force the singularity of objects. Sometimes it seems redundant to force a single object mechanism, but if this mechanism is lightweight, the benefits of conveying intent will be better than the cost of implementing these mechanisms.
The most common use of the singleton mode is as follows: Use a private constructor, a static variable, and a static method to control and restrict instantiation. To ensure thread security, add lock.
Public class Singleton
{
Private Static Singleton theinstance = NULL;
Private Singleton (){}
Public static Singleton instance
{
Get
{
If (theinstance = NULL)
Theinstance = new Singleton ();
Return theinstance;
}
}
}
We can see that the static instance object will be created only once. The Singleton mode applies in many places, such as creating an application. Program The root object, the unique instance of the database connection, and so on. If you want to constrain an existing class through a derived class and do not mind that all its Callers must call the instance () method to obtain access, it is appropriate to use the singleton mode.
In the monostate mode, all the variables in the object are converted to static. I don't know if the monostate mode is very practical. I have never encountered it in actual use. This is just for understanding.