Design Pattern 17: Singleton)
Singleton mode:
Make sure that a class has only one instantiated object and provides a method to access this object.
UML diagram:
It mainly includes:
Singleton (LoadBalancer): defines a method to operate on a unique object; creates and operates on this unique object.
In C ++, the singleton mode is implemented through static member variables and static methods.
# Include
Class Singleton {public: // here we need to define this method as static Singleton * getInstance (); private: Singleton () {} private: // The static member function can only operate on static member variables, so the instance should also be a static Singleton * instance;}; // The initialization Singleton * Singleton of static member variables :: instance = NULL; Singleton * Singleton: getInstance () {if (instance = NULL) instance = new Singleton (); return instance;} int main () {Singleton * s1 = Singleton: getInstance (); Singleton * s2 = Singleton: getInstance (); if (s1 = s2) std :: cout <"s1 and s2 are the same object" <
Execution output: a real example used to randomly schedule a server to process requests.
# Include
# Include
# Include
# Include
# Include
# Include
Using namespace std; class LoadBalancer {public: static LoadBalancer * getInstance (); string getServer () {int I = rand () % 5; return servers [I];} private: loadBalancer () {servers. push_back ("server I"); servers. push_back ("server II"); servers. push_back ("server III"); servers. push_back ("server IV"); servers. push_back ("server V");} private: staticLoadBalancer * instance; vector
Servers;}; LoadBalancer * LoadBalancer: instance = NULL; LoadBalancer * LoadBalancer: getInstance () {if (instance = NULL) instance = new LoadBalancer (); return instance ;} int main () {srand (time (0); LoadBalancer * load1 = LoadBalancer: getInstance (); LoadBalancer * load2 = LoadBalancer: getInstance (); cout <
GetServer () <
GetServer () <
GetServer () <
GetServer () <
GetServer () <
GetServer () <
GetServer () <
GetServer () <
GetServer () <
GetServer () <
GetServer () <
GetServer () <
Execution output: