From 2fd30aba5003b219b26699ccda0409c4191c6a73 Mon Sep 17 00:00:00 2001 From: Ian Dinwoodie Date: Mon, 29 Apr 2019 20:06:03 -0400 Subject: [PATCH] Added singleton example. --- README.md | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 6b75cd6..fede6ee 100644 --- a/README.md +++ b/README.md @@ -717,7 +717,39 @@ makes your code tightly coupled plus mocking the singleton could be difficult. #### Programmatic Example -TODO +To create a singleton, make the constructor private, disable cloning, and create +a static variable to house the instance. + +```cpp +class President +{ + public: + static President& getInstance() + { + static President instance; + return instance; + } + + private: + President() + { + } + + ~President() + { + } +}; +``` + +Here is how this can be used: + +```cpp +President& president1 = President::getInstance(); +President& president2 = President::getInstance(); + +// There can only be 1 president, so they must be the same. +assert(&president1 == &president2); +``` #### When To Use