Singleton mode and monostate Mode

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.