#include "stdafx.h"
#include <iostream>
using namespace std;
class Operation
{
public:
double GetNumA(){return m_numberA;}
double GetNumB(){return m_numberB;}
void SetNumA(double value){m_numberA = value;}
void SetNumB(double value){m_numberB = value;}
virtual double GetResult(){double result = 0; return result;}
private:
double m_numberA;
double m_numberB;
};
class OperationAdd : public Operation
{
virtual double GetResult()
{
double result = 0;
result = GetNumA() + GetNumB();
return result;
}
};
class OperationSub : public Operation
{
virtual double GetResult()
{
double result = 0;
result = GetNumA() - GetNumB();
return result;
}
};
class OperationMul : public Operation
{
virtual double GetResult()
{
double result = 0;
result = GetNumA() * GetNumB();
return result;
}
};
class OperationDiv : public Operation
{
virtual double GetResult()
{
double result = 0;
if (GetNumB() == 0)
{
}
result = GetNumA() / GetNumB();
return result;
}
};
// class OperationSqrt : public Operation
// {
// virtual double GetResult()
// {
// double result = 0;
// if ()
// {
// }
// }
// };
class OperationFactory
{
public:
static Operation* CreateOprate(char operate)
{
switch(operate)
{
case '+':
return new OperationAdd();
break;
case '-':
return new OperationSub();
break;
case '*':
return new OperationMul();
break;
case '/':
return new OperationDiv();
break;
}
return NULL;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
double NumA, NumB;
char operation;
cout<<"输入A:";
cin>>NumA;
cout<<"输入操作符:";
cin>>operation;
cout<<"输入B:";
cin>>NumB;
Operation *Oper;
Oper = OperationFactory::CreateOprate(operation);
if (!Oper)
{
return 0;
}
Oper->SetNumA(NumA);
Oper->SetNumB(NumB);
cout<<"运算结果:"<<Oper->GetResult()<<endl;
delete Oper;
return 0;
}
适用性
在下列情况下可以使用Factory Method模式:
• 当一个类不知道它所必须创建的对象的类的时候。
• 当一个类希望由它的子类来指定它所创建的对象的时候。
• 当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候。
参考《大话设计模式》