Design Patterns 3: Factory Method
阿新 • • 發佈:2018-12-13
定義一個介面(Creator)用以建立物件,由子類(ConcreteCreator)決定建立物件的型別(Product或ConcreteProduct...)
struct Product {}; struct ConcreteProduct : Product {}; struct Creator { virtual Product* FactoryMethod() { return new Product; } void AnOperation() { product = FactoryMethod(); } private: Product * product; }; struct ConcreteCreator : Creator { Product* FactoryMethod() override { return new ConcreteProduct; } }; int main() { Creator* p = new ConcreteCreator; p->AnOperation();//ConcreteCreator::FactoryMethod() get called }