简单工厂模式
简单工厂模式是属于设计模式中的创建性模式,一般是使用静态方法,通过接收不同的参数,返回不同类型的对象实例,下面以大话设计模式中的计算器来举例。计算器一般常见的是四种运算法则,加减乘除。客户端传入需要运算的符号时,会返回该运算的对象实例,进行相应的计算。扩展性较差,添加一个新的运算法则需要修改工厂类Factory,下面是计算器的类图。
下面来看看具体的代码:
/***计算器**简单的工厂类**/
#include <iostream>
#include <string>
using namespace std;
enum OPER_TYPE{
OPER_NULL = -1,
OPER_ADD =0,
OPERA_MINS,
OPERA_MUL,
OPERA_DIV
};
class Operation{ //定义一个基类对象
public:
Operation(){
m_num1 = 0.0;
m_num2 = 0.0;
}
virtual ~Operation(){
}
void setNum(double num1,double num2){
m_num1 = num1;
m_num2 = num2;
}
virtual double GetResult() =0;
public:
int m_num1;
int m_num2;
};
class AddOpera:public Operation{
public:
double GetResult()
{
return m_num1 + m_num2;
}
};
class MinsOpera:public Operation{
public:
double GetResult()
{
return m_num1 - m_num2;
}
};
class MulOpera:public Operation{
public:
double GetResult()
{
return m_num1 * m_num2*1.0;
}
};
class DivOpera:public Operation{
public:
double GetResult(){
if(m_num2 ==0)
{
cout << " it is must not 0" << endl;
return 0;
}
else
{
return m_num1/m_num2;
}
}
};
class Factory{
public:
Factory(){
oper = NULL;
}
public:
void CreateFactor(string op){
switch(get_oper_type(op)){
case OPER_ADD:
oper = new AddOpera();
break;
case OPERA_MINS:
oper = new MinsOpera();
break;
case OPERA_MUL:
oper = new MulOpera();
break;
case OPERA_DIV:
oper = new DivOpera();
break;
default:
cout <<"** input is error ***" << endl;
}
}
OPER_TYPE get_oper_type(string op){
if(op =="+"){
return OPER_ADD;
}
else if(op == "-"){
return OPERA_MINS;
}
else if(op == "*"){
return OPERA_MUL;
}
else if(op == "/"){
return OPERA_DIV;
}
else{
return OPER_NULL;
}
}
Operation* GetType(){
return oper;
}
private:
Operation* oper;
};
int main()
{
Factory fac;
fac.CreateFactor("*");
Operation* oper1 = fac.GetType();
oper1->setNum(1.3,3.0);
double result = oper1->GetResult();
cout << "***the last result is :" << result << endl;
return 0;
}