子弹 の VISIONS

NEVER back down ~~
欢迎交流:[email: waker615@gmail.com][msn: ztwaker2008@hotmail.com][skype:ztwaker]

C++博客 首页 新随笔 联系 聚合 管理
  112 Posts :: 34 Stories :: 77 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 阅读(103) 评论(0)  编辑 收藏 引用 所属分类: 1.2 闲人杂语

专题:Android  iPad jQuery Chrome OS

博客园首页  IT新闻  知识库  学英语  C++程序员招聘
标题  
姓名  
主页
验证码 *
内容(提交失败后,可以通过“恢复上次提交”恢复刚刚提交的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
[使用Ctrl+Enter键可以直接提交]
每天10分钟,轻松学英语
网站导航: