| 1 | = Singleton = |
| 2 | |
| 3 | == Description == |
| 4 | |
| 5 | The [wiki:singleton] is an important design-pattern in advanced c++ coding. A singleton is a class, that allows only one existing instance at a time. This is achieved by overloading the constructor as a private function and the implementation of a static funciton that returns a pointer to the only existing instance (or creates the instance if it's not already existing). The pointer itself is stored in a static variable. This variable must be statically set to zero before you access the [wiki:singleton] the first time. |
| 6 | |
| 7 | This way you can retrieve a pointer to the [wiki:singleton] and access its member functions everywhere in the code without using ugly static objects or completely static classes. |
| 8 | |
| 9 | == Example == |
| 10 | |
| 11 | {{{ |
| 12 | #!cpp |
| 13 | class SlaveSingleton |
| 14 | { |
| 15 | public: |
| 16 | static SlaveSingleton* getSingleton() |
| 17 | { |
| 18 | if (!pointer_s) |
| 19 | pointer_s = new SlaveSingleton(); |
| 20 | |
| 21 | return pointer_s; |
| 22 | } |
| 23 | |
| 24 | void sendToWork() |
| 25 | { this->motivation_--; } |
| 26 | |
| 27 | void bash() |
| 28 | { this->health_ -= 10; this->motivation_++; } |
| 29 | |
| 30 | void feed() |
| 31 | { this->health_ += 5; } |
| 32 | |
| 33 | private: |
| 34 | SlaveSingleton() : health_(100), motivation_(0) |
| 35 | { std::cout << "The slave is born." << std::endl; } |
| 36 | |
| 37 | SlaveSingleton* pointer_s; |
| 38 | int health_; |
| 39 | int motivation_; |
| 40 | }; |
| 41 | |
| 42 | SlaveSingleton* SlaveSingleton::pointer_s = 0; |
| 43 | }}} |
| 44 | |
| 45 | {{{ |
| 46 | #!cpp |
| 47 | SlaveSingleton::getSingleton()->bash(); |
| 48 | SlaveSingleton::getSingleton()->sendToWork(); |
| 49 | }}} |