Introduction:
1. The purpose of the Singleton mode: to ensure that a class has only one instance and provides global access to that instance.
2. The singleton mode, also known as the single-piece mode, the list mode, is probably the most widely used design pattern. The intent is to ensure that a class has only one instance and provides a global access point to access it, which is shared by all program modules.
How does a singleton pattern implement only one instance?? Disables copy constructors to prevent copying.
You can also define multiple instances by explicitly defining them.
such as noncopyable A, B; Although copying is prohibited, you can define multiple objects.
So we make the constructor private so that we can't explicitly define multiple objects.
So how do you instantiate this class if you set the constructor to private? We didn't learn it before. If the constructor is set to private, this is not available, then is it meaningless?
How to solve this problem? Use the curve to salvation: Define a static global function inside the class, let it call the constructor for us, because the function is inside the class, so you can access the private constructor.
1. How to construct a non-replicable class.
1#include <iostream>2#include"Thread.h"3#include <stdlib.h>4 using namespacestd;5 6 //have hidden trouble under multi-threading7 classSingleton8 {9 Public:Ten StaticSingleton *getinstance () One { A if(Pinstance_ = = NULL)//Switching of Threads - { -:: Sleep (1); thePinstance_ =NewSingleton; - } - - returnPinstance_; + } - Private: + Singleton () {} A at StaticSingleton *pinstance_;//static members can be called directly externally - }; - -Singleton *singleton::p instance_ =NULL; - - in classTestthread: PublicThread - { to Public: + voidRun () - { thecout << singleton::getinstance () <<Endl; *cout << singleton::getinstance () <<Endl; $ }Panax Notoginseng }; - the intMainintargcChar Const*argv[]) + { A //Singleton S; ERROR the + - //test proves that there is a competition problem in this code under multithreading $ $Testthread threads[ A]; - for(intIX =0; IX! = A; ++ix) - { the Threads[ix].start (); - }Wuyi the for(intIX =0; IX! = A; ++ix) - { Wu Threads[ix].join (); - } About return 0; $}
C + + Learning path: A single example template