大话设计模式 --- 简单工厂模式

说的是简单的二元数学运算的问题:加减乘除等。

书里是用非C++语言描述的,不过我还是喜欢C++多一点,下面改成了C++版。

操作基类:

class Operation:

{

public:

Operation(): m_numA (0), m_numB(0){}

virtual double GetResult(){return 0;}

void setOperationNum( double numA,double numB )

{

m_numA = numA;

m_numB = numB;

}

private:

double m_numA;

double m_numB;

};

加法类:

class OperationAdd: public Operation

{

public:

virtual double GetResult()

{

return m_numA + m_numB;

}

}

类似实现 减法类 OperationSub 乘法类 OperationMul 等

再实现运算工厂类:

class OperationFactory:

{

public:

Operation * createOperate( const string& operate )

{

Operation* oper;

switch(operate )

{

case "+": oper = new OperationAdd();break;

case "-": oper = new OperationSub();break;

... ...

}

}

}

实际应用:

Operation*oper;

OperationFactory factory;

oper = factory.createOperate("+");

oper->setOperationNum(2,3);

double result = oper->GetResult();

delete oper;

你可能感兴趣的:(简单工厂模式)