When you need to control the number of instances of a class and the caller can access the instance from a public access point.
2. Applicable scenarios
1. When the class can only have one instance and the customer can access it from a well-known access point. 2. When this unique instance should be extensible through subclass, and the customer should be able to use an extended instance without changing the code.
3. Comment
Advantages: 1. controlled access to a unique instance. Because the singleton class encapsulates its unique instance, it can strictly control how and when the customer accesses it. 2. Narrow the namespace. Singleton mode is an improvement for global variables. It prevents global variables that store unique instances from polluting namespace. 3. the refined Singleton class that allows operations and representations can have child classes, and it is easy to configure an application using the instance of this extension class. You can use the instance of the class you need to configure the application at runtime. 4. Allow variable target instances. This mode makes it easy for you to change your mind and allow multiple instances of the singleton class. In addition, you can control the number of instances used by the application in the same way. Only the operations that allow access to the singleton instance need to be changed.
4. Mode Structure
Singleton defines a getinstance operation that allows customers to access its unique instance. Etinstance is a class operation (that is, a class method in Smalltalk and a static member function in C ++ ). It may be responsible for creating its own unique instance.
5. Case Study
(1) A modern chocolate factory has a computer-controlled chocolate boiler. The boiler is used to combine chocolate and milk and then deliver them to the next stage to make them chocolate bars. Choc-o-holic has a chocolate boiler controller used to control boiler activities, such: when the boiler is empty, the raw material can be added, the raw material in the boiler is allowed to boil, milk and chocolate are discharged, and the existing raw material in the furnace is required and has been boiled. In the case of multiple chocolateboiler (chocolate boiler), we do not necessarily follow the procedures we have to limit, resulting in many bad situations, so chocolateboiler must be designed into a single piece.
6. Reference
[1] gof: design mode.
[2] Baidu Encyclopedia: http://baike.baidu.com/view/3745751.htm.
[3] http://blog.csdn.net/hguisu/article/details/7515416.