大话设计模式01-简单工厂模式-2020-9-18

一、简单工厂模式简介

	简单工厂模式:当定义了多个子类来继承父类以实现不同扩展时,**为了避免将多个子类暴露给客户端,减少耦合性,可以新增一个简单工厂类,负责根据传入参数初始化不同子类对象。**

二、实例

	实现一个简单的计算器类,可以完成加减乘除运算,类图如下所示。
	![在这里插入图片描述](https://img-blog.csdnimg.cn/20200918155020321.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM3MjkyOTgy,size_16,color_FFFFFF,t_70#pic_center)

	c++实现代码如下:
#include
#include 
using namespace std;
//1-简单工厂模式:实现计算器
class Operator
{
     
public:
	Operator(double iVal1, double iVal2) :m_val1(iVal1), m_val2(iVal2){
     };
	virtual double getResult() = 0;
	virtual ~Operator(){
     };
protected:
	double m_val1;
	double m_val2;
};

class OperatorAdd :public Operator
{
     
public:
	OperatorAdd(double iVal1, double iVal2) :Operator(iVal1,iVal2){
     };
	double getResult() override
	{
     
		return m_val1 + m_val2; 
	}
};

class OperatorSub :public Operator
{
     
public:
	OperatorSub(double iVal1, double iVal2) :Operator(iVal1, iVal2){
     };
	double getResult() override
	{
     
		return m_val1 - m_val2;
	}
};

class OperatorMuti :public Operator
{
     
public:
	OperatorMuti(double iVal1, double iVal2) :Operator(iVal1, iVal2){
     };
	double getResult() override
	{
     
		return m_val1 * m_val2;
	}
};

class OperatorDev :public Operator
{
     
public:
	OperatorDev(double iVal1, double iVal2) :Operator(iVal1, iVal2){
     };
	double getResult() override
	{
     
		if (m_val2==0)
		{
     
			cout << "除数不能为0!" << endl;
			throw exception("除数不能为0!");
		}
		return m_val1 / m_val2;
	}
};

class OperatorFactory
{
     
public:
	static Operator *createOperator(double iVal1,char c,double iVal2)
	{
     
		switch (c)
		{
     
			case '+':
			{
     
				return new OperatorAdd(iVal1, iVal2);
			}
			case '-':
			{
     
				return new OperatorSub(iVal1, iVal2);
			}
			case '*':
			{
     
				return new OperatorMuti(iVal1, iVal2);
			}
			case '/':
			{
     
				return new OperatorDev(iVal1, iVal2);
			}
			default:
			{
     
				cout<<"运算符非法!"<<endl;
				throw exception("运算符非法!");
			}
		}
	}
	static void destoryOperator(Operator *&ipOper)
	{
     
		delete ipOper;
		ipOper = NULL;
	}
};

int main()
{
     
	Operator *pOper = OperatorFactory::createOperator(10.23, '+', -9.87);
	cout << pOper->getResult() << endl;
	OperatorFactory::destoryOperator(pOper);
	system("pause");
}

你可能感兴趣的:(大话设计模式,设计模式,c++)