std::string SomeOperation()const{ // 在工厂主类中 生产 产品,FactoryMethod 是由对应的子类重写了,因此不同的子类会返回不同的产品 // 然后再 调用产品完成特定的功能 Product* product = this->FactoryMethod(); std::string result = "Creator: The same creator's code has just worked with " + product->Operation(); delete product; return result; } };
voidClientCode(const Creator& creator){ // ... std::cout << "Client: I'm not aware of the creator's class, but it still works.\n" << creator.SomeOperation() << std::endl; // ... }
intmain(){ std::cout << "App: Launched with the ConcreteCreator1.\n"; Creator* creator = newConcreteCreator1(); ClientCode(*creator); std::cout << std::endl; std::cout << "App: Launched with the ConcreteCreator2.\n"; Creator* creator2 = newConcreteCreator2(); ClientCode(*creator2);