[设计模式] Understand Design Patterns -- Factory Method

[设计模式] Understand Design Patterns -- Factory Method

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!!

你可能感兴趣的:([设计模式] Understand Design Patterns -- Factory Method)