您的位置:首页 > 编程语言 > C语言/C++

设计模式C++版:第零式简单工厂

2016-08-15 19:36 330 查看
在前面介绍C++基础的时候,我们写了一个简单地计算类 http://blog.csdn.net/thedarkfairytale/article/details/51750971 。考虑到易扩展和复用的特性,下面使用设计模式的简单工厂类实现一下(自己对着代码动手敲一下,感觉绝对不同):
class Operation
{
public:
virtual double getresult(){ return 0; }
public:
double m_firstnum;
double m_secondnum;
};

class OperationAdd :public Operation
{
public:
double getresult(){ return m_firstnum + m_secondnum; }
};

class OperationSub :public Operation
{

public:
double getresult(){ return m_firstnum - m_secondnum; }
};

class OperationMul :public Operation
{

public:
double  getresult(){ return m_firstnum * m_secondnum; }
};

class OperationDiv :public Operation
{
public:
double getresult()
{
if (0 != m_secondnum)
{
return m_firstnum / m_secondnum;
}
else
{
printf("the second number can't be zero!");
return 0;
}
}
};
enum class ENUMOPERATION   //枚举类 避免隐式转换的污染
{
ADD = 1,
SUB = 2,
MUL = 3,
DIV = 4
};

class SimpleFactory
{
public:
SimpleFactory():m_oper(nullptr){}
Operation &createoperaton(ENUMOPERATION oper);

private:
Operation * m_oper;
};

Operation& SimpleFactory::createoperaton(ENUMOPERATION oper)
{
if (m_oper!=nullptr)
{
delete m_oper;
m_oper = nullptr;
}

switch (oper)
{

case ENUMOPERATION::ADD:
m_oper = new OperationAdd;
break;
case ENUMOPERATION::SUB:
m_oper = new OperationSub;
break;
case ENUMOPERATION::MUL:
m_oper = new OperationMul;
break;
case ENUMOPERATION::DIV:
m_oper = new OperationDiv;
break;
default:
m_oper = new OperationAdd;
break;
}
return *m_oper;
}
int main()
{
Operation *oper;
SimpleFactory factory;
oper = &factory.createoperaton(ENUMOPERATION::ADD);
oper->m_firstnum = 12;
oper->m_secondnum = 21;
cout << oper->getresult() <<endl;
return 0;
}


使用简单工厂模式后的代码,和之前简单的封装以后对比发现,之前的单一接口,都变成了一个运算类,这样的好处是,我们隔离了各种运算,想要复用其中的一个算法不用把其他的也都牵连进来。

如果我们修改加法,则不必和减法产生任何关联,同理修改乘法也不必和除法有什么关联,另外我们添加其他运算方式也方便同时不至于一个类变得太大。如果我们只想使用复用加法和减法,那么我们只需把加减法的运算类拿过来使用即可,不必和乘除法有什么联系。但简单工厂也是很多不足,比如每次添加或减少运算类,都要修改工厂类,在一定程度上降低了工厂类的封装性。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: