Singleton mode (Singleton)
Intentions
Single-Case mode
Ensure that a class has only one instance and provides a global access point to access it.
Applicability
- When a class can have only one instance and the customer can access it from a well-known access point.
- When this unique instance should be extensible by subclasses, and the customer should be able to use an extended instance without changing the code.
Singleton mode (Singleton)I have 6 beautiful wives, their husbands are me, I am our home husband Sigleton, they just say "husband", all refers to the same person, that is I (just had a dream, which has such a good thing) Singleton mode: Singleton mode to ensure that a class has only one instance, It also instantiates itself and provides this instance singleton pattern to the entire system. Singleton mode should only be used when there is a real "single instance" requirement.
Class Singleton{private:static Singleton * single; Singleton () {}public:static Singleton * getinstance () {if (single = NULL) Single = new Singleton (), return single;}; Singleton * Singleton::single = null;int _tmain (int argc, _TCHAR argv[]) {Singleton * S1 = singleton::getinstance (); Singleton * s2 = singleton::getinstance (); if (S1 = = s2) cout << "Same" << endl;else cout << "Different" &L t;< Endl;}
The implementation point of the Singleton mode: 1. The constructor is private (external cannot be new), and its own object as a member variable is also private and static, because the function of the returned instance is static, so the member variable should also be static
C + + design mode from 0 attack to single case mode