简单工厂模式
主要用于创建对象。新添加类时不会影响已有的代码系统。核心思想是用一个工厂类根据输入条件的不同生成不同的对象,然后根据多态决定调用哪一个对象。
优点:适用于不同的情况创建不同的对象
缺点:客户端必须要知道基类和工厂类,耦合性差。
(工厂类和基类为关联关系)
下面是代码:
#include
//基类
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 MulOPeration : public COperation
{
public:
virtual double GetResult()
{
return m_nFirst * m_nSecond;
}
};
//除法类
class DivOPeration : public COperation
{
public:
virtual double GetResult()
{
return m_nFirst/m_nSecond;
}
};
//工厂类
class CCalculatorFactory
{
public:
static COperation* Create(char cOperation);
};
COperation* CCalculatorFactory::Create(char cOperation)
{
COperation *oper;
switch(cOperation)
{
case '+':
oper = new AddOperation();
break;
case '-':
oper = new SubOperation();
break;
case '*':
oper = new MulOPeration();
break;
case '/':
oper = new DivOPeration();
break;
default:
std::cout << "no so char" << std::endl;
break;
}
return oper;
}
//客户端
int main()
{
int a,b;
std::cin>>a>>b;
COperation *op = CCalculatorFactory::Create('-');
op->m_nFirst = a;
op->m_nSecond = b;
std::cout << op->GetResult() << std::endl;
return 0;
}
阅读(739) | 评论(0) | 转发(0) |