The Monostate pattern is usually referred to as a conceptual Singleton.
It ensures that every instances of a class have the same data.
Monostate pattern and Singleton pattern are actually the two faces of the same medal :
- The Monostate pattern forces a behaviour - One data representation to all the instances.
- The Singleton pattern forces a structural constraint - One instance of the class.
Nothing fancy !
All you need to do is to declare every data member of the class static.
This way, any number of instances can be created (in a transparent way) but they all share the same data.
NB : You will need getter/setter functions for every data members.
Pros
- Transparency :
- Monostate pattern, unlike Singleton pattern, is transparent to the user.
- There is no way to tell a class uses the Monostate pattern unless being aware of the implementation.
- Derivability :
- Derivates of a MonoState are MonoStates (since they all share the same static variables).
- Well-defined creation/destruction :
- Static variables have a well-defined lifetime.
- Inheritence :
- Easy to inherit, use and maintain.
- Conversions :
- Making an existing class similar to a Singleton is easy without writting extra code.
Cons
- Efficiency :
- Allows for many objects creation/destruction which are CPU costly.
- Presence :
- Static variables take up space irrespective of the fact these objects are used or not.