Design Pattern --- Creator
class Product {}; class ProductA : public Product { public: ProductA() { cout <<"ProductA" <<endl; } }; class ProductB : public Product { public: ProductB() { cout <<"ProductB" <<endl; } }; class Creator { public: virtual Product *anOperation() = 0; virtual Product *factoryMethod() { return anOperation(); } }; class CreatorA : public Creator { public: virtual Product *anOperation() override { return new ProductA; } }; class CreatorB : public Creator { public: virtual Product *anOperation() override { return new ProductB; } }; int main(int argc, char *argv[]) { CreatorA creatorA; Product *product = creatorA.factoryMethod(); // creator.createProductB(); // TODO: Release memory. return 0; }
Creator 是一个创建其它对象的接口。被创建的对象应该是一个复杂的,需要很多 ‘anOperation’ 操作的对象。
相对于 Builder 模式, 此模式更倾向于使用子类构造不同的子部件, Creator 中有一个函数负责多态的调用子部件并拼装. 而 Builder 则是使用另一个 Directory 类拼装 Builder 子类产生的子部件.