【1】什么是简单工厂模式?核心思想:用一个工厂来根据输入的条件产生不同的类,然后根据不同类的virtual函数得到不同的结果。理解:根据条件生成不同的实例。利用多态的特性,调用同名方法,不同的实例将得到不同的结果。【2】代码示例如下:代码如下:
#include#include using namespace std;/* * 运算基类 */class Operation{public: double numberA; double numberB;public: 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 operFactory{public: static Operation *createOperation(char c) { switch (c) { case '+': return new addOperation; break; case '-': return new subOperation; break; case '*': return new mulOperation; break; case '/': return new divOperation; break; default: break; } }}; /* * 客户端应用示例 */void main(){ Operation *oper = operFactory::createOperation('+'); oper->numberA = 9; oper->numberB = 99; cout << oper->getResult() << endl;}