Factory Method

Series - Design Patterns

Factory Method

In order to seprate the resource allocation from client, cause client only need to care about the logic.

In fact, factory is a bridge between client and the object need to be created.

Avoid unnecessary invoke object construct function, for some resources, we don’t need to call the constructor or cpoy constructor, instead we do a shallow copy if there is no references type in the class.

pros.

  • remove the allocate logic from client

cons.

  • lack of flexibility, need to modify when new create logics are needed

According to the cons. of simple factory, in order to avoid frequently modified the code in simple factory, we create an general interface factory which is the base class of all factory, it has a virtual function call Create(), every derived class from this need to over write this function, so that in the client we can use it like:

c++

// factory side
class Fruit;

class Factory() {
    virtual Fruit create() = 0;
}

class Apple : public Fruit;

class AppleFactory() : public Factory {
    virtual Fruit create() override {
        return Apple();
    }
}

// client side
void main() {
    Apple apps[3];
    Factory appFac = new AppleFactory();
    for(size_t idx = 0; idx < 3; idx++) {
        apps[idx] = Factory.create();
    }
}

simple factory: one factory -> produce serveral products

simple factory upgraded: one abstract factory -> produce related products factory -> produce related products