主要用于创建对象。新添加类时不会影响以前的系统代码。原理是创建一个工厂类,根据输入条件在其内部产生不同的类,再根据不同类的virtual函数得到不同结果。
代码实现:
#include<iostream>
using namespace std;
//基类
class COperation {
public:
int m_nFirst;
int m_nSecond;
virtual double GetResult()
{
double dResult=0;
return dResult;
}
};
//加法
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;
cout<<"请输入两个操作数,空格分开:"<<endl;
cin>>a>>b;
COperation* op=CCalculatorFactory::Create('-');
op->m_nFirst=a;
op->m_nSecond=b;
cout<<op->GetResult()<<endl;
return 0;
}