Single-case mode with 23 design modes

Source: Internet
Author: User

We also often encounter a similar situation, in order to save system resources, sometimes need to ensure that a class in the system only one instance, when the unique instance is created successfully, we can no longer create another object of the same type, all operations can only be based on this unique instance. In order to ensure the uniqueness of the object, we can use the singleton mode, which is the motive of the singleton mode.

Defined:

Singleton mode (Singleton pattern): Ensures that a class has only one instance, and instantiates it itself and provides it to the entire system, a class called a singleton class that provides methods for global access. Singleton mode is an object-creation pattern.


So, how do you create a singleton object?

We can start with three steps to create:

1.because each useNewkeyword to instantiateaclass will produce a new object in order to ensure that theThe uniqueness of the instance, we need to prohibit the external direct use of the classNewto create the object, so you need tothe classchange the visibility of the constructor toPrivate, as shown in the following code:

/* Private construction method to prevent instantiation of */private Singleton () {}
2.change the constructor toPrivateHow do I create an object after retouching it? Don't worry, although the outside of the class can no longer be usedNewto create the object, but thethe classcan be created internally, so we canclassThis unique instance is created and saved in the In order for the outside world to access this unique instance, you need toTaskManagerdefines a staticTaskManagertype of private member variable, in order to guarantee the encapsulation of member variables, we will SingletonThe visibility of the type's singleton object is set to private, as shown in the following code:

private static Singleton Singleton = null;
3.But how does the outside world use the member variable and when does it instantiate that member variable? The answer is to add a public static method, as shown in the following code:
/* Static Engineering method, create instance *  /public static Singleton getinstance () {if (Singleton = = null) {//must add this judgment, otherwise each call to getinstance () will be new A new object to point to the new object, the original data will not be reinitialized. or private static Singleton Singleton =new Singleton (), do not have to judge, directly return to Singletonsynchronized (Singleton) {//Synchronized code block, Ensure thread safety in a multithreaded environment if (singleton = = null) {//To add if judgment statement, because when there are two threads a, b simultaneously into the first if judgment statement, if there is no if statement in the synchronization code block, Then a thread enters synchronized locking new to unlock the object, and the B thread enters the synchronized will also be a new object, so that the wired thread security problem Singleton = new Singleton ();}} return singleton;}
in thegetinstance ()method, first JudgeSingletonwhether the object exists, if it does not exist (that is, Singleton= = NULL), use theNewkeyword to create a newSingletontype ofSingletonobject, and then returns the newly createdSingletonobject, otherwise return directly to the existingSingletonobject.

Outside the class we can't directly create a new Span style= "FONT-SIZE:16PX; line-height:26px; Font-family: ' Times New Roman ' "> getinstance () The

The singleton mode has three points: first, there can be only one instance of a class, and the other is that it must create this instance on its own, and thirdly, it must provide this instance to the whole system on its own.

So, let's look at a complete singleton pattern code:

public class Singleton {private static Singleton Singleton = Null;//static method cannot be used as a non-static global variable, the assignment to null is to delay the creation of the object/* Private construction method, Prevent instantiation of */private Singleton () {}/* Static engineering method, create instance *  /public static Singleton getinstance () {if (Singleton = = null) {// Must add this judgment, otherwise each call to getinstance () will come out a new object, so that it points to the new object, the original data will not be reinitialized. or private static Singleton Singleton =new Singleton (), do not have to judge, directly return to Singletonsynchronized (Singleton) {//Synchronized code block, Ensure thread safety in a multithreaded environment if (singleton = = null) {//To add if judgment statement, because when there are two threads a, b simultaneously into the first if judgment statement, if there is no if statement in the synchronization code block, Then a thread enters synchronized locking new to unlock the object, and the B thread enters the synchronized will also be a new object, so that the wired thread security problem Singleton = new Singleton ();}} return singleton;}}




Single-case mode with 23 design modes

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.