[Zen Reading Notes in design mode] 007_23 Design Mode 1: Singleton Mode

Source: Internet
Author: User

Preface

Today, I started to learn the first mode of 23 design modes-singleton mode. I have read many blog posts about Singleton mode on the Internet. Today, I am going to explain the design patterns in the Zen of design patterns. The author is still very careful. The only pity is that the author explained the singleton mode in Java, and I used C ++ since my work last year. Based on the principle of what to learn and what to use, I will use C ++ to record the learning results. I hope this blog will share what I learned with readers in the garden like me.

Body

1. Actual scenarios of Singleton Mode

At the beginning of the article, I used the Emperor's analogy to the singleton. However, I have a better example, and I want to hear it one by one. There is a star and nine planets in the solar system. At least I went to school on nine planets. Later, I was removed because Pluto was too small. However, I still think the number 9 is better. For example, the nine planets and the nine stars are even better. What is the singleton model equivalent to in this solar system? Sun. Yes, Sun. The earth said, "I want sunshine; Venus said," I want sunshine. All these sunlight come from the same sun. That is to say, there is only one object in the solar system. This is the singleton model. No matter which planet in the solar system I am on, the sunlight I get is from the same sun.

2. Implementation of Singleton mode (1) -- Non-synchronous Singleton mode and lazy Singleton Mode

1 # include <iostream> 2 using namespace STD; 3 4 class Singleton {5 public: 6 static Singleton * getinstance () {7 if (instance = NULL) {8 instance = new Singleton (); 9} 10 return instance; 11} 12 private: 13 static Singleton * instance; 14 Singleton (){}; // This class cannot be initialized externally. 15}; 16 Singleton * singleton: instance; // note that the instance in the class is only declared, static variables must be 17 18 int main () {19 Singleton * instance = singleton: getinstance (); 20 system ("pause"); 21 return 0; 22}

Source code implementation

The above code is a complete console program, which can be compiled and run correctly in vs2010 pro. Next we will introduce the key points of this program:

■ The Singleton class has a static member pointer variable, which is shared by the entire class.

■ The Singleton class has a private no-argument constructor. This shows that the object cannot be instantiated by the constructor outside the class.

■ Singleton class has a getinstance method, which is used internally to instantiate the instance member pointer variable

The preceding Singleton implementation is also called the lazy Singleton mode. Why? Because a singleton-like member instance is initialized only when it is called, it is called a lazy Singleton implementation.

Disadvantages

Is there any problem with the above implementation? Yes. In multi-threaded scenarios, the above Code can easily generate multiple instances. Why? I drew a picture as follows:

As you can see, in a multi-threaded environment, if you still follow the above Code implementation, the instance will be created multiple times, so the above Code is still problematic, it is only in a multi-threaded environment.

3. Singleton mode Implementation (2) -- synchronization Singleton mode and ELE. Me Singleton Mode

For the multi-threaded problem in 2, we can easily end with the following code.

1 # include <iostream> 2 using namespace STD; 3 4 class Singleton {5 public: 6 static Singleton getinstance () {7 return instance; 8} 9 private: 10 static Singleton instance; 11 Singleton () {}; // The class cannot be initialized externally. 12}; 13 Singleton singleton: instance; // note that the instance in the class is only declared, static variables must be defined outside the class 14 15 int main () {16 Singleton instance = singleton: getinstance (); 17 system ("pause"); 18 return 0; 19}

The above code is created when the class is created, so that the instance will not be created multiple times with multiple threads. The program is interpreted as follows:

■ The Singleton class has a static instance variable instead of a pointer.

■ The Singleton class has a private constructor, which is the same as the lazy style.

Why is the above implementation called a Chinese-style Singleton? Because the above implementation instantiated a static member variable of this class before calling Singleton's getinstance.

Disadvantages

The above implementation has ended the multi-thread problem. Is there any problem? Yes. Take a closer look and find the following sentence: Singleton instance = singleton: getinstance (); The created object is assigned to the instance through the value assignment operator of Singleton, which is not good, although there is always only one instance in the singleton class. But it is copied, so it is not a singleton. What should I do? The method is simple. You can change the copy constructor and value assignment operator of the singleton class to private. The modified code is as follows:

1 # include <iostream> 2 using namespace STD; 3 4 class Singleton {5 public: 6 static Singleton getinstance () {7 return instance; 8} 9 private: 10 static Singleton instance; 11 Singleton () {}; // This class cannot be initialized externally. 12 Singleton (const Singleton & Singleton); 13 Singleton & operator = (const Singleton &); 14 }; 15 Singleton singleton: instance; // note that the instance in the class is only declared, and the static variable must be defined 16 17 int main () {18 // Singleton instance = singleton :: getinstance (); // failed to compile 19 system ("pause"); 20 return 0; 21}

4. Destroy objects in singleton Mode

For the lazy Singleton implementation, we can see the new word in the getinstance function. It must be deleted using Delete. Otherwise, memory overflow may occur, so how can we use code to implement it? You can append an destructor by referring to the following code:

1 class Singleton {2 public: 3 static Singleton * getinstance () {4 If (instance = NULL) {5 instance = new Singleton (); 6} 7 return instance; 8} 9 ~ Singleton () {10 if (instance! = NULL) {11 Delete instance; 12} 13} 14 private: 15 static Singleton * instance; 16 Singleton () {}; // This class cannot be initialized externally for 17 }; 18 Singleton * singleton: instance; // note that the instance in the class is only declared, and the static variable must be out-of-class.

Others

In Java, there are many issues to solve multithreading, which will not be discussed in this article. If you are interested, refer to: multithreading.

Summary

You can use the lazy Singleton implementation method without considering multithreading. In a multi-threaded environment, it is best to use a hungry Chinese Singleton implementation method. At the same time, you must change the constructors, Default constructors, and value assignment operators to private.

PS: Please note the error. Thank you.

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.