Definition:
A class has only one instance and provides a global access point to access it.
Key points:
1. The class can only have one instance;
2. You must create this instance on your own;
3. You must provide this instance to the entire system.
Implementation 1: Singleton mode structureCode
Singleton. h:
View code
# Ifndef _ singleton_h _# Define_ Singleton_h _ClassSingleton {Public:StaticSingleton *Getinstance ();Protected: Singleton ();Private:StaticSingleton *_ Instance ;};# Endif
Singleton. cpp:
View code
# Include " Singleton. h " # Include <Iostream> Using Namespace STD; Singleton * Singleton: _ instance = 0 ; Singleton: Singleton () {cout < " Create Singleton... " < Endl;} Singleton * Singleton: getinstance (){ If ( 0 = _ Instance) {_ instance = New Singleton ();} Else {Cout < " Already exist " < Endl ;} Return _ Instance ;}
Main. cpp:
# Include"Singleton. h"IntMain () {Singleton* T =Singleton: getinstance (); t->Getinstance ();Return 0;}
Implementation 2: printer instances
Singleton. h:
View code
# Ifndef _ singleton_h _ # Define _ Singleton_h _ Class Singleton { Public : Static Singleton * Getinstance (); Void Printsomething ( Const Char * Str2print ); Protected : Singleton (); Private : Static Singleton * _ Instance; Int Count ;}; # Endif
Singleton. cpp:
View code
# Include " Singleton. h " # Include <Iostream> Using Namespace STD; Singleton * Singleton: _ instance = 0 ; Singleton: Singleton () {cout < " Create Singleton... " < Endl; count = 0 ;} Singleton * Singleton: getinstance (){ If ( 0 = _ Instance) {_ instance = New Singleton ();} Else {Cout < " Instance already exist " < Endl ;} Return _ Instance ;} Void Singleton: printsomething ( Const Char * Str2print) {cout < " Printer is now working, the sequence: " <++ Count < Endl; cout <Str2print <Endl; cout < " Done \ n " < Endl ;}
Main. cpp:
# Include"Singleton. h"IntMain () {Singleton* T1 =Singleton: getinstance (); T1->Getinstance (); T1-> Printsomething ("T1"); Singleton* T2 =Singleton: getinstance (); T2-> Printsomething ("T2");Return 0;}
MAKEFILE file:
Cc = g ++Cflags=-G-O2-wallall: Make singletonsingleton: Singleton. O \Main.O$ {CC}-O Singleton main. O Singleton.Oclean: Rm-RF Singleton Rm-f *.O. Cpp.O:$ (CC) $ (cflags)-c-o $ *. o $ <
Running effect:
We can see that the count of the print order count is continuous, and there is only one printing device in the system.