#include <iostream> using namespace std; /* Operation 基类和子类 */ class Operation { public: void setOperands(const int operA = 0, const int operB = 0) {m_operandA = operA; m_operandB = operB;} virtual int getRlt() = 0; protected: int m_operandA; int m_operandB; }; class OperationAdd : public Operation { public: int getRlt() {return m_operandA + m_operandB;} }; class OperationSub : public Operation { public: int getRlt() {return m_operandA - m_operandB;} }; /* SimpleFactory 类 */ class SimpleFactory { public: static Operation* createOperation(char oper); }; Operation* SimpleFactory::createOperation(char oper) { Operation *operation = NULL; switch (oper) { case '+': operation = new OperationAdd(); break; case '-': operation = new OperationSub(); break; } return operation; } /* 测试 */ void main() { Operation *oper = NULL; oper = SimpleFactory::createOperation('+'); oper->setOperands(32, 23); cout<<"Result: "<<oper->getRlt()<<endl; delete oper; oper = SimpleFactory::createOperation('-'); oper->setOperands(32, 23); cout<<"Result: "<<oper->getRlt()<<endl; delete oper; system("pause"); }
基本思想:
为什么使用simple factory模式?
当基类的派生类很多时,比如OperationAdd,OperationSub, OperationMulti etc. 使用它们时需要通过各个名字来创建,
如果使用simple facotry类来管理,对用户而言
1. 逻辑就更清晰
2. 更抽象,对用户隐藏了各个派生类。
对开发者而言,逻辑同样更清晰了,易于维护。