Design Mode (5) SINGLETON)

Source: Internet
Author: User

Problem focus:

Let the class itself save its unique instance and ensure that no other instance can be created.
The Singleton mode is relatively simple to use, but when the singleton class has sub-classes and the number is not scheduled, you need to use a registry to manage it. This part is not clear and will be supplemented later.
Purpose: ensure that a class has only one instance and provide a global access point to it.
Motivation: A digital filter can only have one A/D converter, and an accounting system can only be used by one company.
Requirement: ensure that a class has only one instance and the instance is easy to access.
A global variable is an object that can be accessed, but it cannot prevent you from instantiating multiple objects.
Solution: Let the class itself be responsible for saving its unique instance. This class can ensure that no other instance can be created, and it can provide a method to access the instance. This is the singleton mode.
Applicability: The Singleton mode can be used in the following scenarios: when a class can only have one instance and the customer can access it from a well-known access point, when this unique instance should be extensible through subclass, in addition, the customer should be able to use an extended instance structure without changing the Code:
Participant: Singleton: defines an Instance operation that allows the customer to access its unique Instance. An Instance is a class operation (that is, a static member function in C ++ ). It may be responsible for creating its own unique instance. Collaboration: the customer can only access a Singleton Instance through the Singleton Instance operation.
Effect: Advantages of Singleton mode: controlled access to a unique instance: strict control over how and when a customer accesses it to narrow down the namespace: an improvement in global variables, this prevents global variables that store unique instances from polluting the namespace and allows refinement of operations and representations: The Singleton class can have sub-classes, in addition, it is easy to configure an application using this extension class instance. You can use the instance of the class you need to configure the application at runtime. Allow variable target instances: Allow multiple instances of the Singleton class. In addition, you can use the same method to control the number of instances used by the application. More flexible than class operations: another way to encapsulate single-piece functions is to simply use class operations (static member functions in C ++ ), however, it is difficult to change the design to allow a class to have multiple instances.
Implementation: The following are implementation considerations when using the Singleton mode. 1) Ensure a unique instance: The operation for creating this instance is hidden behind a class operation, it ensures that only one instance is created for the Demo:
Class Singleton {public: static Singleton * Instance (); protected: Singleton (); // The constructor is of the protected type, customers who directly instantiate Singleton In a view will get an error message during compilation. Private: static Singleton * _ instance;}; Singleton * Singleton: _ instance = 0; Singleton * Singleton: Instance () {if (_ instance = 0) {_ instance = new Singleton; // The Initialization is not performed until the instance is used for the first time. }}
The customer only accesses this single piece through the Instance member function.
Note that defining a single piece as a global or static object depends on automatic Initialization is not enough for the implementation of c ++ for three reasons: we cannot guarantee that only one static object will be declared. We may not initialize each information required by an instance. C ++ does not define the call sequence of the constructor of the global object on the conversion unit. used or not, global/static objects are created. 2) create a Singleton sub-class single-piece Registry: Create a ing between the string name and the Singleton class. When an Instance requires a Singleton, refer to the Registry to request Singleton by name. A single-piece registry means that the Instance no longer needs to know all possible Singleton classes or instances. All it needs is a public interface of all Singleton classes. This interface includes operations on the registry.
Class Singleton {public: static void Register (const char * name, Singleton *); static Singleton * Instance (); protected: static Singleton * Lookup (const char * name): private: static Singleton * _ instance; static List
 
  
* _ Registry; // each NameSingletonPair maps a name to a singleton .};
 

The Lookup operation is performed based on the name of the Order instance. Assume that an environment variable specifies the name of the required single piece.
Singleton* Singleton::Instance () {    if (_instance == 0)     {        const char* singletonName = getenv("SINGLETON");        _instace = Lookup(singletonName);    }    return _instance;};

Two Methods for registering the Singleton class: 1 register in the constructor:
MySingleton::MySingleton() {    Singleton::Register("MySingleton*, this");}

2. Define a static instance for implementation
static MySingleton theSingleton;
The Singleton class is no longer responsible for creating Singleton instances. Its primary responsibility is to make the selected Singleton objects accessible in the system. Static object methods have one disadvantage: all possible Singleton subclass instances must be created and are not registered.
Code example: Use Singleton mode to override the MazeFactory class.
Ignore the case of a single example class
class MazeFactory {public:    static MazeFactory* Instance();protected:    MazeFactory();private:    static MazeFactory* _instance;};MazeFactory* MazeFactory::_instance = 0;MazeFactory* MazeFactory::Instance () {    if (_instance ==0) {        _instance = new MazeFactory;    }}

If multiple sub-classes of MazeFactory exist. In addition, the application must decide which subclass to use. In this example, we will use environment variables to select the type of the maze and add code based on the value of the environment variable to instantiate the appropriate MazeFactory subclass.
MazeFactory* MazeFactory::Instance () {    if(_instance == 0)    {        const char* mazeStyle = getenv("MAZESTYLE");        if (strcmp(mazeStylem, "bombed") == 0)        {            _instance = new BombedMazeFactory;        }        else if (strcmp(mazeStyle, "enchanted") == 0)        {            _instance = new EnchantedMazeFactory;        }        // ... ... other possible subclass        else        {            _instance = new MazeFactory;        }    }    return _instance}


 

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.