Notes for a single mode:
1) To design a single pattern, we first need to privatize the constructor so as not to allow external access, so the outside can only obtain a new class through the provided functions.
(2) In the single mode of C ++, remember to initialize a class outside the class; otherwise, there may be memory errors.
3) The unique class must be static.
Program:
# Ifndef _ SINGLETON_H # define _ SINGLETON_H # include
# Include
Using namespace std; class DuGuJiuJian {string FounderName; DuGuJiuJian (string name): FounderName (name ){}~ DuGuJiuJian () {if (Founder) delete Founder;} public: void poJian () {cout <" ...... \ N ";} void poDao () {cout <" broken knife ...... \ N ";} inline static DuGuJiuJian * getInstance (string name =" No Name ") {if (! Founder) {Founder = new DuGuJiuJian (name);} return Founder;} string getFounder () {return FounderName;} private: static DuGuJiuJian * Founder;}; DuGuJiuJian * DuGuJiuJian :: founder = nullptr; void SingletonDuGuJiuJian_Run () {DuGuJiuJian * jian = DuGuJiuJian: getInstance ("dedicated for defeat"); cout <"Founder is:" <
GetFounder () <
GetFounder () <
PoDao (); cout <" Chong"; jian_2-> poJian (); cout <"Founder is:" <
GetFounder () <
Run:
Because it is a single model, only one founder is dedicated to defeat.
Of course, this class is not very perfect. For example, there may be problems when there are multiple threads, the memory should be released well, and temporary static classes can be used.
However, this is the concept of this mode.