Step-by-step analysis of Singleton Mode

Source: Internet
Author: User

What is Singleton mode?

It is used to ensure that a class has an instance in the system and is responsible for self-instantiation and providing access to the instance to the entire system.
 
Why is the singleton mode used?
 
There are two situations in Object-Oriented Programming:
1. In most cases, our programmers define the class constructor as a public access permission, so that they can create class objects in sequence.
2. In some special cases, it makes no sense to allow other classes to freely create the class, or even bring some negative effects. After all, creating an object will bring about related costs and system overhead. for example, a system may have only one window manager, and more Window managers are redundant.
Therefore, we need a class to create only one instance, and this class provides a public access point to access it. This is the singleton mode.
 
How to Use Singleton mode?
Singleton mode has the following three features:
Static private variable.
Private constructor.
Public static entry method.
 
If we understand the above three features, the entire Singleton model framework will be illustrated.
So why does the singleton mode have the above three features?
 
The first feature is static private variables. this class must cache the created objects. Otherwise, the class does not know whether the object has been created, so it cannot guarantee that only one object can be created, therefore, this class needs to use an attribute to save the previously created object. This attribute needs to be accessed by a static method in this class, so this attribute must be modified using static.
 
Second feature: private constructor. because the singleton mode requires that this class cannot be created by other classes, but only allows this class to create one object, in order to avoid other classes from creating such instances freely, by modifying the constructor of this class using private, the constructor of this class is hidden, and other classes cannot create objects of this class.
 
Third feature: public static entry method. according to the good encapsulation principle, once the constructor of the class is hidden, a public method must be provided as the Access Point of the class to create the class object, and the method must be modified using static, why? Because the class object does not exist when you call this method, that is to say, it is impossible to call this method. It can only be a class and must be modified using static.
 
The preceding three features are the core points of the singleton mode. The code in singleton mode is used to demonstrate the whole Singleton mode process:
 
Singleton
[Java]
/**
* Simple Singleton Mode
* @ Author jnqqls
*
*/
Publicclass Singleton {

// Use static variables to cache the created instance.
Private static Singleton instance = null;

// Use private to hide the constructor.
PrivateSingleton (){

}

// Provides a static method to return the Singleton instance.
// Add control to ensure that there is only one instance.
Publicstatic Singleton getInstance (){

If (instance = null ){

// Create a Singleton object and save it in the instance.
Instance = new Singleton ();
}

Returninstance;
}

}


 
 
Client: TestSingleton
 
[Java]
/**
* The client program is used to view the effect of Singleton mode.
* @ Author jnqqls
*
*/
Publicclass TestSingleton {

/**
* @ Param args
*/
Publicstatic void main (String [] args ){

// Instantiate the first singleton object
SingletoninstanceOne = Singleton. getInstance ();

// Instantiate the second singleton object
SingletoninstanceTwo = Singleton. getInstance ();

// Check whether two instances are the same object?
System. out. println (instanceOne. equals (instanceOne ));
System. out. println (instanceOne = instanceTwo );

}

}


Output result:
True
True
 
The code above shows that we can implement custom control through methods to ensure that the Singleton class has only one instance, therefore, we can see from the final running result that the two objects generated in the main method of the TestSingleton class are actually the same object.

In what scenarios is the singleton mode suitable?
If this class does not have any member variables that can be modified, that is to say, this class has no state. If there is a member variable that can be modified, thread security issues will occur. Therefore, it is not recommended to use this class. because the singleton mode cannot be inherited, there is no way to expand and its implementation cannot be expanded. it is suitable for reading configuration files in singleton mode.

The following article describes how to read the configuration file in singleton mode.

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.