Design patterns – Singleton / Multiton 2


Hello guys,

Today I’ll write about Singletons and Multitons.

Singleton pattern allows you to create and use only one instance of a class, and it used when you are sure that only one is needed.

They are used for example as resource holders or loggers. In order to assure that we have only one class, we need to have the following:

  • One instance of that class – which will be a static instance inside the class
  • A static function that will return the single instance

In order to assure that we can have only one instance, we will need to do the following:

  • The constructor of the class must be private (the only instance can be created internally and will be done so in the static function that will also be used to retrieve it)
  • The copy constructor and assignment operator shall be made private so nobody can clone that object or create a copy. For C++11, we also need to do the same for the move constructor/operator.

Multiton pattern allows you to have multiple singletons (thus the name), but only one for each specified type. It will act as a container that will keep all the class instances and will return to the user based on the key specified.

For multiton, we need to have:

  • A private map that will contain the singletons based on keys
  • A function that returns (or creates if not available) the singleton instance based on keys

For example, we have a map based on strings ->

multiton::getInstance(“string1”) -> creates and returns string1 singleton instance

multiton::getInstance(“string1”) -> returns the same string1 singleton instance

multiton::getInstance(“string2”) -> creates and returns string2 singleton instance

If we need to have a limited number of singletons, we can use other type than strings, such as enums.

The full code can be found at the following link:

 

https://github.com/badearobert/cplusplus/tree/master/DesignPatterns_Singleton

https://github.com/badearobert/cplusplus/tree/master/DesignPatterns_Multiton

Regards,

Robert

https://github.com/badearobert/cplusplus


Leave a comment

Your email address will not be published.

2 thoughts on “Design patterns – Singleton / Multiton