将《大话设计模式》书中的简单工厂模式(Simple Factory)用C++代码重写了一遍,如有错误,望指正。
SimpleFactory.h:
#ifndef _SIMPLEFACTORY_H
#define _SIMPLEFACTORY_H
//运用简单工厂模式设计一个计算器
#include <iostream>
#include <string>
using namespace std;
class COperation
{
public:
COperation();
virtual double GetResult(); //设置为虚函数,从而在子类中重载它
double m_dNumA;
double m_dNumB;
protected:
private:
};
class COperationAdd : public COperation
{
public:
double GetResult();
protected:
private:
};
class COperationSub : public COperation
{
public:
double GetResult();
protected:
private:
};
class COperationMul : public COperation
{
public:
double GetResult();
protected:
private:
};
class COperationDiv : public COperation
{
public:
double GetResult();
protected:
private:
};
class COperationFactory //工厂类
{
public:
COperation* CreateOperation(const char &ch);
protected:
private:
};
#endif
SimpleFactory.cpp:
#include "SimpleFactory.h"
/************************************************************************/
/* COperation类 */
/************************************************************************/
double COperation::GetResult()
{
double result = 0;
return result;
}
COperation::COperation()
{
m_dNumA = 0;
m_dNumB = 0;
}
/************************************************************************/
/* COperationAdd类 */
/************************************************************************/
double COperationAdd::GetResult()
{
double result = m_dNumA + m_dNumB ;
return result;
}
/************************************************************************/
/* COperationSub类 */
/************************************************************************/
double COperationSub::GetResult()
{
double result = m_dNumA - m_dNumB ;
return result;
}
/************************************************************************/
/* COperationMul类 */
/************************************************************************/
double COperationMul::GetResult()
{
double result = m_dNumA * m_dNumB ;
return result;
}
/************************************************************************/
/* COperationDiv类 */
/************************************************************************/
double COperationDiv::GetResult()
{
double result = 0 ;
if (m_dNumB != 0)
result = m_dNumA / m_dNumB;
else
result = 999999999;
return result;
}
/************************************************************************/
/* COperationFactory类 */
/************************************************************************/
COperation* COperationFactory::CreateOperation(const char &ch)
{
COperation *oper;
switch (ch)
{
case '+':
oper = new COperationAdd;
break;
case '-':
oper = new COperationSub;
break;
case '*':
oper = new COperationMul;
break;
case '/':
oper = new COperationDiv;
break;
}
return oper;
}
main.cpp:
#include <iostream>
#include "SimpleFactory.h"
using namespace std;
int main()
{
COperationFactory factory;
COperation *opr = factory.CreateOperation('*');
opr->m_dNumA=1;
opr->m_dNumB=2;
cout<<opr->GetResult()<<endl;
delete []opr;
return 0;
}