Monostate Design Pattern explained with simple example

Monostate design pattern is a singleton design pattern variation in which a class will act like a singleton but this class will look like a normal class. This design pattern states that all data member of monostate classes are static but any number of instances can be created in the program.

Before going ahead have a look at Design pattern simplified version and Singleton design pattern.

Some important points:

  • All data members must be static.
  • There Must be getter/setter function for data members.
  • There should not be any restrictions on instantiation of object for this class.
  • Since, data members are static, hence all instance will share same data.

Let’s have a look on the Monostate design pattern example:

class Monostate
{
private:
    static int m_data;
    static string m_name;
 
public:
    Monostate ()
    {
        // Normal constructors
    }

    void setValues (int data, string name)
    {
        m_data = data;
        m_name = name;
    }

    void printValues()
    {
        cout<<"Monostate class data value "<<m_data<<" and name "<<m_name<<endl;
    }

    int getData ()
    {
        return m_data;
    }

    string getName ()
    {
        return m_name;
    }

    ~Monostate()
    {
        cout << "In Destructor" << endl;
    }

};

int Monostate::m_data = 0;
string Monostate::m_name = "";

Advantage of Monostate design pattern:

  • It’s easy to inherit, use and maintain.
  • Making an existing class similar to singleton can be easily done using Monostate design pattern provided the system works fine. This method can save huge effort of writing extra codes.

Disadvantage of Monostate design pattern:

  • Since all data members of this class are static, they will always take memory irrespective of fact whether these objects are needed or not.
  • The biggest problem with this pattern is that it allows many object creation which will eat significant amount of CPU in creation/destruction of object.

Leave a Reply

Your email address will not be published. Required fields are marked *