今天把项目都做完后,就开始继续学设计模式。刚看了简单的工厂模式,感觉之前对面向对象这个概念实在是太浅了,在我的观念中,一直认为程序只要能运行,没有bug就是成功的,但是看了设计模式之后,发现原来的观念实在是太表面化了,没有深入的理解面向对象这个概念。我是看了《大话设计模式》这本书开始学的,感觉讲的简单易懂,而我另外一本书讲的就是晦涩了,理解起来很难。
简单的工厂模式。就拿一个简单的四则运算来说,输入两个数和符号,输出结果,如果在学习设计模式之前,我可能会这么写:
#include <iostream>
using namespace std;
int main()
{
double numA, numB;
char ope;
cout<<"请输入数字A:";
cin>>numA;
cout<<"请输入运算符(+、-、*、/):";
cin>>ope;
cout<<"请输入数字B:";
cin>>numB;
cout<<"结果为:";
switch(ope)
{
case '+':
{
cout<<numA+numB;
break;
}
case '-':
{
cout<<numA-numB;
break;
}
case '*':
{
cout<<numA*numB;
break;
}
case '/':
{
if(numB == 0)
{
cout<<endl<<"除数不能为0!";
break;
}
else
{
cout<<numA/numB;
break;
}
}
}
cout<<endl;
return 0;
}
但是,这并不是面向对象,只是一个用C语言写才cpp文件而已,最明显的就是,如果要我这个时候改变其中一个算法,或是添加一个算法,我就得大幅度的改动,这样的话,对程序的可维护性来说就很差。
相反,简单的工厂模式,就是将这些算法步骤、具体的过程封装到了一个或多个类中,然后设计一个工厂类,专门用来生成算法类,这个时候c++的三大特点也都派上了用场:
#include <iostream>
#include <string>
#include <exception>
using namespace std;
class Operate //算法类基类
{
double NumberA; //操作数NumberA
double NumberB; //操作数NumberB
public:
void setNumA(double A){NumberA = A;} //NumberA赋值
void setNumB(double B){NumberB = B;} //NumberB赋值
double getNumA(){return NumberA;} //获取NumberA值
double getNumB(){return NumberB;} //获取NumberB值
virtual double getresult() //虚函数 用于实现多态 实现派生类的getresult()函数
{
double result;
return result;
}
};
class OperateADD : public Operate //加法算法类
{
double getresult()
{
double result;
double numA = this->getNumA();
double numB = this->getNumB();
result = numA + numB;
return result;
}
};
class OperateSUB : public Operate //减法算法类
{
double getresult()
{
double result;
double numA = this->getNumA();
double numB = this->getNumB();
result = numA - numB;
return result;
}
};
class OperateMUL : public Operate //乘法算法类
{
double getresult()
{
double result;
double numA = this->getNumA();
double numB = this->getNumB();
result = numA * numB;
return result;
}
};
class OperateDIV : public Operate //除法算法类
{
double getresult()
{
double result;
double numA = this->getNumA();
double numB = this->getNumB();
try
{
if(numB == 0) //除数为0时 抛出异常
{
throw "除数不能为0!";
}
else
{
result = numA / numB;
return numB;
}
}
catch(const char* msg)
{
cout<<msg<<endl;
}
}
};
class OperatorFactory //工厂类 用于生成算法类
{
Operate *oper; //声明一个算法类指针
public:
Operate* operatorcreate(char operate) //由运算符来生成算法类
{
switch(operate)
{
case '+':
{
oper = new OperateADD;
break;
}
case '-':
{
oper = new OperateSUB;
break;
}
case '*':
{
oper = new OperateMUL;
break;
}
case '/':
{
oper = new OperateDIV;
break;
}
}
return oper;
}
};
int main()
{
try
{
double numA, numB;
char ope;
cout<<"请输入数字A:";
cin>>numA;
cout<<"请输入运算符(+、-、*、/):";
cin>>ope;
cout<<"请输入数字B:";
cin>>numB;
OperatorFactory OFT; //定义一个工厂类对象,调用operatorcreate()函数
Operate *my_oper = OFT.operatorcreate(ope); //根据运算符创建算法类对象
my_oper->setNumA(numA);
my_oper->setNumB(numB);
cout<<"结果为:"<<my_oper->getresult()<<endl;
}
catch(exception &e)
{
cout<<"您的输入有误!"<<endl;
}
return 0;
}