子弹 の VISIONS

NEVER back down ~~

C++博客 首页 新随笔 联系 聚合 管理
  112 Posts :: 34 Stories :: 99 Comments :: 0 Trackbacks

Factory Method

// interface
class People
{
public:
    virtual void doWhat() =0;
    virtual string type() const =0;
};

class Male : public People
{
public:
    virtual void doWhat();
    virtual string type() const;
    static  People* creator();
};

class Female : public People
{
public:
    virtual void doWhat();
    virtual string type() const;
    static  People* creator();
};


// interface
typedef People* (*CreateFcn)();
class PeopleFactory
{
public:
    static People* producePeople(const string& type);
    static addCreateFcn(const string& type, CreateFcn creator);

private:
    static map<string, CreateFcn> createFcns;
};

People* PeopleFactory::producePeople(const string& type)
{
    //***1
    CreateFcn creator= createFcns[type];
    return creator();
}

---- test ----
void f()
{
    //***2
    const string t("Male"); //or "Female"
    People* p = PeopleFactory::producePeople(t);
    p->doWhat();   
    delete p;
}

---- extension ----
class Hemophrodite : public People
{
    virtual void doWhat();
    virtual string type() const;
    static  People* creator();
};

void g()
{
    //***3
    const string newType = "Hemophrodite";
    PeopleFactory::addCreateFcn(newType, Hemophrodite::creator);

    // usage
    const string t("Hemophrodite");
    People* p = PeopleFactory::producePeople(t);
    p->doWhat();   
    delete p;
}

Cool!! OCP!!

---------
Key point:

1. How does the Factory Method create the instance
    of classes through their type names?
   How could this method follow the OCP?

2. Where does the type name come from?
 -- config file
 -- registry
 -- other method

3. About extension
  
----------
Interface classes:
    People & PeopleFactory


enjoy it!!
posted on 2008-07-17 12:43 子弹のVISIONS 阅读(783) 评论(1)  编辑 收藏 引用 所属分类: 1.2 闲人杂语

Feedback

# re: [设计模式] Understand Design Patterns -- Factory Method 2014-07-06 17:07 Emma
用什么可以提供给那些谁需要,我相信你的网站是好的。 http://www.friv5gamer.com  回复  更多评论
  


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理