3.1 motivation for Singleton Mode
For some classes in a software system, we do not need to create multiple instances. For example, Windows Task Manager, as shown in 3-1, we can make such an attempt, in Windows, right-click the "Task Bar" and choose "Start Task Manager" multiple times in the pop-up menu. Can you open Multiple Task Manager windows? If you have multiple task managers on your desktop, I will invite you to dinner (Note: Except for computer viruses or Windows Kernel modification without permission ). Generally, no matter how many times we start task management, only one task manager window is displayed in windows. That is to say, in a Windows system, the task manager is unique. Why is it designed like this? We can analyze it from the following two aspects: first, if multiple windows are displayed and the content of these windows is completely consistent, all of them are repeated objects, this will inevitably waste system resources, the task manager needs to obtain a lot of information during system operation, which consumes a certain amount of system resources, including CPU resources and memory resources. It is shameful to waste resources, in addition, there is no need to display multiple windows with the same content. Second, if the content of the pop-up windows is inconsistent, the problem becomes more serious, this means that the system resource usage and process, service, and other information are in multiple States at a certain moment. For example, in the Job Manager window A, the "CPU usage" is 10%, window B shows that "CPU usage" is 15%. Which one is true? This is purely a "teasing" user, which brings misunderstandings to users and is not desirable. It can be seen that the Windows Task Manager is only important in the system.
Figure 3-1 Windows Task Manager
Back to actual development, we often encounter similar situations. To save system resources, we sometimes need to ensure that a class in the system has only one unique instance. After this unique instance is created successfully, we cannot create another object of the same type. All operations can only be performed based on this unique instance. To ensure the uniqueness of objects, we can implement it through the singleton mode, which is the motivation of the singleton mode.
3.2 Singleton mode Overview
Next we will simulate the implementation of the Windows Task Manager. Assume that the class of the task manager is named TASKMANAGER. the TaskManager class contains a large number of member methods, such as the constructor taskmanager (), display the process method displayprocesses () and the service method displayservices (). The sample code for this class is as follows:
Class taskmanager {public taskmanager (){......} // Initialization window public void displayprocesses (){......} // Display the process public void displayservices (){......} // Display the service ......}
To ensure the uniqueness of the Windows Task Manager, We Need To refactor the class in the following three steps:
(1) Each time the new keyword is used to instantiate the TaskManager class, a new object is generated. To ensure the uniqueness of the TaskManager instance, we need to use new to create an object outside the ban class, therefore, you need to change the TaskManager constructor visibility to private, as shown in the following code:
private TaskManager() {……}
(2) how to create an object after modifying the constructor to private? Don't worry. Although New cannot be used to create objects outside the class, it can still be created inside TASKMANAGER. Visibility is only valid outside the class. Therefore, we can create and save this unique instance in TASKMANAGER. To allow external access to this unique instance, You need to define a static private member variable of the TaskManager type in TaskManager, as shown in the following code:
private static TaskManager tm = null;
(3) to ensure the encapsulation of the member variables, we set the visibility of the TM object of the TaskManager type to private. But how can we use this member variable and when to instantiate it? The answer is to add a public static method, as shown in the following code:
public static TaskManager getInstance(){ if (tm == null) { tm = new TaskManager(); } return tm;}
In the getinstance () method, first determine whether the TM object exists. If it does not exist (TM = NULL), use the new keyword to create a new TM object of the TaskManager type, the newly created TM object is returned. Otherwise, the existing TM object is directly returned.
It should be noted that the modifier of the getinstance () method should first be a public method to be used by other external objects. Secondly, it uses the static keyword, that is, it is a static method that can be accessed directly outside the class name without creating a taskmanager object. In fact, it cannot be created outside the class because the constructor is private.
|
Thoughts Why do we define the member variable TM as a static variable? |
|
Through the above three steps, we have completed the design of a simplest Singleton class. The complete code is as follows:
Class taskmanager {Private Static taskmanager TM = NULL; private taskmanager (){......} // Initialization window public void displayprocesses (){......} // Display the process public void displayservices (){......} // Display the public static taskmanager getinstance () {If (TM = NULL) {TM = new taskmanager () ;}return TM ;}......}
You cannot directly create a new taskmanager object outside the class, but you can use the code TASKMANAGER. getinstance () is used to access the instance object. When you call the getinstance () method for the first time, a unique instance is created. When you call the call again, the instance created for the first time is returned to ensure the uniqueness of the Instance Object.
The above code is also the most typical Implementation Method of Singleton mode. With the above foundation, it is very easy to understand the definition and structure of Singleton mode. The Singleton mode is defined as follows:
Singleton pattern: ensure that a class has only one instance, and instantiate and provide this instance to the entire system. This class is called a singleton class, it provides global access methods. The Singleton mode is an object creation mode. |
The Singleton mode has three key points: one is that a class can only have one instance; the other is that it must create the instance; the third is that it must provide the instance to the entire system.
The Singleton mode is the simplest design mode. Its core structure only contains a special class called Singleton class. The Singleton mode structure is 3-2:
The Singleton mode structure only contains one Singleton role:
● Singleton (Singleton): only one instance is generated within the singleton class. It also provides a static getinstance () Factory method to allow customers to access its unique instance; to prevent external instantiation, the constructor is designed to be private. Within the singleton class, a static object of the singleton type is defined as a unique instance of external sharing.
[Author: Liu Wei http://blog.csdn.net/lovelion]