Factory Design Pattern


This is one of creational design pattern provides the best ways to create an object.
In factory design pattern sub class decide whose object should be created on the basis of argument.

checklist:

1. Create abstract base class.
2. Derive sub classes from that base class & override all the functions of abstract base class.
3. Create a Factory class which will provide a object of Derive sub class as per requirement.


Client just needs to make call to library’s guifactory CreateWidget method and pass the type it wants without worrying about the actual implementation of creation of objects



Here we implemented the widgets for GUI library.

#include<iostream>
using namespace std;

enum widgettype
{
    BUTTON,
    SLIDER,
    CHECKBOX
};

class Widget
{
    public:
        virtual void Init()=0;
        virtual void Show()=0;
        virtual void Update(int value)=0;
};

class Button : public Widget
{
    public:
        void Init()
        {
            cout<<"initialising button"<<endl;
        }
        void Show()
        {
            cout<<"show button"<<endl;
        }
        void Update(int value)
        {
            cout<<"update button"<<value<<endl;
        }
};

class Slider : public Widget
{
    public:
    void Init()
    {
        cout<<"initialising slider"<<endl;
    }
    void Show()
    {
        cout<<"show slider"<<endl;
    }
    void Update(int value)
    {
        cout<<"update slider"<<value<<endl;
    }
};

class CheckBox : public Widget
{
    public:
        void Init()
        {
            cout<<"initialising checkbox"<<endl;
        }
        void Show()
        {
            cout<<"show checkbox"<<endl;
        }
        void Update(int value)
        {
            cout<<"update checkbox : "<<value<<endl;
        }
};

class GUIFactory
{
    public:
        GUIFactory()
        {
            cout<<"GUIFactory created"<<endl<<endl;
        }
        Widget* CreateWidget(widgettype type)
        {
            if(type == BUTTON)
                return new Button;
            else if(type == SLIDER)
                return new Slider;
            else if(type == CHECKBOX)
                return new CheckBox;
        }
};

int main()
{
    GUIFactory factory;
    Widget *ptr = factory.CreateWidget(CHECKBOX);
    ptr->Init();
    ptr->Show();
    ptr->Update(2);

    ptr = factory.CreateWidget(BUTTON);
    ptr->Init();
    ptr->Show();
    ptr->Update(3);

    return 0;
}



Comments

Popular posts from this blog

STL Questions

Producer Consumer problem using mutex

Adapter Design Pattern