Single-Case mode
Concept: A class that can create only one object
Implementation key: 1, all constructors must be private (including parameter constructs, copy constructs, assignment operators)
2. Request the object space through the static member function and return the address
3. Define a static tag, record the number of objects, and control
4. The destructor clears the tag to achieve the purpose of repeating the request object, and the destructor is public
5, the assignment operator, copy constructor must also be private, because the compiler default composition of the assignment operators and copy constructors are public, so both functions are to be defined, and not by the editor default composition
Code implementation:
1#include <iostream>2 3 using namespacestd;4 5 class Single6 {7 Private://because all constructors in singleton mode must be private, all constructors for the compiler's default composition are public.8Single () =default;//so at this point all constructors have to be defined once9Single (Constsingle&) =default;Tensingle&operator=(Constsingle&) =default; One A Public: - Static intFlag; - Staticsingle*creat (); the~single ()//The destructor is public - { -Flag =0; - } + }; - + intSingle::flag =0; A atsingle*single::creat () - { - if(Flag = =0) - { -Flag =1; - return(NewSingle ); in } - Else to returnnullptr; + } - the * intMain () $ {Panax NotoginsengSingle *P1 = Single::creat ();//Create an Object -Delete P1;//destroy This object the +Single *P2 = Single::creat ();//Correct: You can create a new object because the previous object has been destroyed ASingle *P3 = Single::creat ();//Error: The class can only have one unique object, so when P3 is created as nullptr the + return 0; -}
The realization of c++--single case model