7/07/2013

Factory method pattern

This pattern is used with polymorphism and template which are representative feature of C++ language. The main advantage of factory method is that when making new object or extending previous object, define new sublayer class and then just overriding member function which is defined as a factory method. Therefore, we don't need to analyze existing source code detaily.

Here is a sample class diagram using Factory method pattern.

Implementation code is below.
sample.h
#include <map>

using namespace std;

typedef struct _controlInfo
{
    unsigned int ctrlId;
    struct _positionInfo
    {
        unsigned int x;
        unsigned int y;
    }Position;
    struct _sizeInfo
    {
        unsigned int width;
        unsigned int height;
    }Size;

}ControlInfo;

class CControlBase
{
public:
    virtual bool Create(const ControlInfo* info) = 0;
};

class CButton : public CControlBase
{
public :
    bool Create(const ControlInfo* info)
    {
        //Make Button
        //...
        //...

        return true;
    }
};

class ControlMaker
{
public :
    void Make(const ControlInfo* info)
    {
        CControlBase *base = CreateControl();
        base->Create(info);
        ctrlMap[info->ctrlId] = base;
    }

protected :
    virtual CControlBase* CreateControl() = 0;

private :
    map<unsigned int, CControlBase *>ctrlMap;
};

template <class ctrlType>
class ConcreteControlMaker : public ControlMaker
{
protected :
    CControlBase* CreateControl() { return new ctrlType; }
};
 

sample.cpp
//
#include "stdafx.h"
#include "Sample.h"

int _tmain(int argc, _TCHAR* argv[])
{  
    //get contrl info by using xml or ini
    ControlInfo* info = NULL;
    GetControlInfo(info);
   
    //if need to make a button
    ConcreteControlMaker<CButton> btn;
    btn.Make(info);
   
    return 0;
}
 
 
Because this pattern delegates sublayer classes to create object, therefore, factory method pattern has advantages when need to divide the responsibility of object creation.

No comments:

Post a Comment