First, we will introduce the simplest and most common design mode: singleton (singleton ).
Intention
Ensure that a class has only one instance and provides a global access point to it.
Examples of known applications
Qt, QCoreApplicationJava, Runtime. getRuntime ()
FAQs
Multi-threaded re-entry and competition will cause two or more instances to be built and cannot find the appropriate time to release the singleton. You can consider atexit
Applicable Environment
A class must have only one instance, and the instance must be accessed by the customer to be extended by the quilt class, but the customer does not need to modify the code
Classic Implementation of Singleton
Here we provide a single-instance implementation for delayed loading (non-delayed loading, including static classes and Global static instances ). The header file is as follows:
class Singleton {public: Singleton * instance();protected: Singleton();private: static Singleton * _instance;};
The source file is as follows:
Singleton * Singleton::_instance = 0;Singleton * Singleton::instance(){ if(!_instance) { _instance = new Singleton(); } return _instance;}
Problem Discussion
The preceding implementation involves several common issues that need to be discussed.
The first is the problem caused by multithreading. if we call the Singleton: instance () method in more than two threads, after the if statement is executed in thread, thread switching occurs and switches to B. After thread B executes the if statement, thread switching occurs again. Switch to C ,......, well, the problem occurs. At most instances with the same number of threads will appear, and each thread returns a different instance after the function instance () is called for the first time. There are two solutions to this problem: locking or dual detection.
Let's talk about locking first. This is logically correct and feasible. However, performance issues are not recommended.
The basic idea of dual detection is to make two non-empty judgments. if is followed by another one, You can google it.
The second is object copy. The above implementation does not set the copy constructor and the value assignment operator to private without implementation. In this way, the client programmer may assign values to the singleton instance.
--------
Well, the Singleton is introduced here. In most cases, the Singleton is used together with other design patterns, such as the factory model. We will use the factory as a singleton.