简单工厂模式,适合不同情况创建不同类对象时使用。
缺陷:客户端必须要知道基类和工厂类,耦合性差。
//算法基类
class COperation
{
public:
virtual double GetResult()=0;
protected:
int m_nFirst;
int m_nSecond;
};
//加法
class AddOperation : public COperation
{
public:
virtual double GetResult()
{
return m_nFirst+m_nSecond;
}
};
//减法
class SubOperation : public COperation
{
public:
virtual double GetResult()
{
return m_nFirst-m_nSecond;
}
};
//工厂类
class CCalculatorFactory
{
public:
static COperation* Create(char cOperator);
};
COperation* CCalculatorFactory::Create(char cOperator)
{
COperation *oper;
switch (cOperator)
{
case '+':
oper=new AddOperation();
break;
case '-':
oper=new SubOperation();
break;
default:
oper=new AddOperation();
break;
}
return oper;
}
客户端
int main()
{
int a,b;
cin>>a>>b;
COperation *op=CCalculatorFactory::Create('-');
op->m_nFirst=a;
op->m_nSecond=b;
cout<<op->GetResult()<<endl;
delete op;
return 0;
}