Design Mode-singleton Mode

Source: Internet
Author: User
The intention of using the single-piece mode is to ensure that a class has only one instance and provide a global access point to it.
Defining a single piece as a global or static object depends on automatic initialization and cannot fully implement the above intent. Although global access points can be provided, this is not enough. The reason is as follows:
1) We cannot guarantee that only one instance of the static object will be declared.
2) We may not have enough information to instantiate each single piece during static initialization. A single piece may need to be calculated later in the program running.
3) C ++ does not define the call sequence of the constructor of global objects on the conversion unit. This means that there is no dependency between a single piece. If yes, errors are inevitable.
4) use the global or static object implementation method to create all single pieces, whether used or not.
Next, let's take a look at how the single-piece mode achieves its original intent and solves the above problems.

Sample Code for a single-piece instance:

[CPP]View plaincopy
  1. Class Singleton
  2. {
  3. Public:
  4. Static Singleton * getinstance ();
  5. Protected:
  6. Singleton ();
  7. PRIVATE:
  8. Static Singleton * m_pinstance;
  9. };
  10. Singleton * singleton: m_pinstance = NULL;
  11. Singleton * singleton: getinstance ()
  12. {
  13. If (m_pinstance = NULL)
  14. {
  15. M_pinstance = new Singleton;
  16. }
  17. Return m_pinstance;
  18. }

Constructors are protected. You cannot create instances of this class by yourself. Therefore, you can only obtain instances of this class through the static member function instance, the static member variables m_pinstance and static member functions ensure that only one instance is created, and the instance is created only at the first access.

The Singleton mode has many advantages:

1) controlled access to a unique instance. The Singleton class encapsulates its unique instance and strictly controls how and when the customer accesses it.
2) narrow down the namespace. The Singleton mode is an improvement on global variables, avoiding the global variables that store unique instances from polluting the namespace.
3) allows the essence of operations and representations. The Singleton class 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 required class to configure the application at runtime.
4) Allow variable target instances. Multiple instances of the singleton class are allowed. You can use the same method to control the number of instances used by the application. Only the operations that allow access to the singleton instance need to be changed.
5) more flexible than class operations.

Next we will consider Singleton in the case of multithreading.

When multithreading occurs, multiple threads may enter the IF (m_pinstance = NULL) clause, resulting in the creation of multiple instances and Memory leakage. Therefore, mutex operations between threads should be added.

Sample Code for multithreading single-piece mode:

[CPP]View plaincopy
  1. Class Singleton
  2. {
  3. Public:
  4. Static Singleton * getinstance ();
  5. Protected:
  6. Singleton ();
  7. PRIVATE:
  8. Static Singleton * m_pinstance;
  9. };
  10. Singleton * singleton: m_pinstance = NULL;
  11. Singleton * singleton: getinstance ()
  12. {
  13. If (m_pinstance = NULL)
  14. {
  15. Lock ();
  16. If (m_pinstance = NULL)
  17. M_pinstance = new Singleton;
  18. Unlock ();
  19. }
  20. Return m_pinstance;
  21. }

The dual-check is used here. The mutual exclusion is considered only during the first creation to improve efficiency.

The above code has another question: when will the space pointed to by m_pinstance be released, and how to complete the instance's destructor. If there are operations such as disabling files and releasing resources in the class destructor, our code must analyze the instance properly at the right time.

Here is a solution to this problem:

[CPP]View plaincopy
  1. Class Singleton
  2. {
  3. Public:
  4. Static Singleton * getinstance ();
  5. Protected:
  6. Singleton ();
  7. PRIVATE:
  8. Static Singleton * m_pinstance;
  9. Class Garbo
  10. {
  11. Public:
  12. ~ Garbo ()
  13. {
  14. Delete singleton: m_pinstance;
  15. }
  16. };
  17. Static Garbo m_garbo;
  18. };
  19. Singleton * singleton: m_pinstance = NULL;
  20. Singleton: Garbo singleton: m_garbo; // do not forget the definition here.
  21. Singleton * singleton: getinstance ()
  22. {
  23. If (m_pinstance = NULL)
  24. {
  25. Lock ();
  26. If (m_pinstance = NULL)
  27. M_pinstance = new Singleton;
  28. Unlock ();
  29. }
  30. Return m_pinstance;
  31. }
The preceding method defines a private embedded class in singleton to prevent this class from being used elsewhere. When the program runs, the system calls the m_garbo destructor of the static member of the singleton class. The destructor releases the m_pinstance instance and performs the destructor.

There is also another method, but this method is complicated to handle thread security issues. For now, thread security is not considered, but only the problem of analysis structure is considered:
(Thread security is not considered ):

[CPP]View plaincopy
  1. Class Singleton
  2. {
  3. Public:
  4. Static Singleton * getinstance ();
  5. Protected:
  6. Singleton ();
  7. };
  8. Singleton * singleton: getinstance ()
  9. {
  10. Static Singleton instance;
  11. Return & instance;
  12. }
This method initializes the class only when getinstance is called for the first time and automatically analyzes the structure at the end of the program. The code is short, which is an effective method. However, no matter whether the class is used or not, space must be allocated for the class, But Initialization is performed only when necessary. The Singleton mode is a simple design mode with many applications. It is often used in combination with other design modes.

Design Mode-singleton Mode

Related Article

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.