【1】什么是工厂方法模式? 定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类当中。核心工厂类不再负责产品的创建,这样核心类成为一个抽象工厂角色,仅负责具体工厂子类必须实现的接口,这样进一步抽象化的好处是使得工厂方法模式可以使系统在不修改具体工厂角色的情况下引进新的产品。 【2】工厂方法模式代码示例 #include <iostream> #include <string> using namespace std; class Operation { public: double numberA; double numberB; virtual double getResult() { return 0; } }; class addOperation : public Operation { double getResult() { return numberA + numberB; } }; class subOperation : public Operation { double getResult() { return numberA - numberB; } }; class mulOperation : public Operation { double getResult() { return numberA * numberB; } }; class divOperation : public Operation { double getResult() { return numberA / numberB; } }; class IFactory { public: virtual Operation *createOperation() = 0; }; class AddFactory : public IFactory { public: static Operation *createOperation() { return new addOperation(); } }; class SubFactory : public IFactory { public: static Operation *createOperation() { return new subOperation(); } }; class MulFactory : public IFactory { public: static Operation *createOperation() { return new mulOperation(); } }; class DivFactory : public IFactory { public: static Operation *createOperation() { return new divOperation(); } }; int main() { Operation *oper = MulFactory::createOperation(); oper->numberA = 9; oper->numberB = 99; cout << oper->getResult() << endl; return 0; }