What is the alternative to the singleton design pattern?
Overview
The monostate pattern is sometimes known as a conceptual singleton or the syntactic sugar over the singleton pattern.
It avoids all the issues that come with having only one instance of a class. Yet, all the instances share the same data. This is mostly performed through the use of static data members. One of the essential features is fully transparent to users, who have no idea they are dealing with a monostate. Users can build as many monostate instances as they wish, and each instance is equal in terms of data access.
Difference
| Monostate | Singleton |
|---|---|
| Having a monostate requires us to behave in a certain way (only one value along all class instances). | A structural limitation is imposed by a singleton (only one instance). |
| The usage is transparent. | The usage is not transparent. |
Example
#include <iostream>#include <string>#include <unordered_map>class Monostate {public:void addNumber(const std::string& na, int numb) {teleBook[na] = numb;}void getEntries () {for (auto ent: teleBook){std::cout << ent.first << ": " << ent.second << '\n';}}private:static std::unordered_map<std::string, int> teleBook;};std::unordered_map<std::string, int> Monostate::teleBook{};int main() {std::cout << '\n';Monostate tele1;Monostate tele2;tele1.addNumber("grimm", 123);tele2.addNumber("huber", 456);tele1.addNumber("smith", 789);tele1.getEntries();std::cout << '\n';tele2.getEntries();std::cout << '\n';}
Explanation
-
Lines 9 to 11: We create a
addNumbermethod to add thenumbandna(name/key which refers to that number) tounordered_map. -
Lines 13 to 17: We create a method named
getEntries()that displays all the entries on the map. -
Line 21: We create
staticunordered_mapof the key-value (stringandint) pair. -
Lines 31 to 32: We create two
Monostateobjects. -
Lines 33 to 35: We use the
tele1.addNumbe()method to add data to the monostate set. -
Lines 37 to 43: The
getEntries()method displays the entries of the set. They both show the same entries because both point to a single set.
Free Resources