第一章 简单工厂模式

一 包含的角色
简单工厂模式包含三个角色:

  • 工厂类Factory:工厂类是用来制造产品的。因此,在Factory中有一个用于制造产品的Create函数或者Generate函数之类的函数。这个函数能够根据“标识符”的不同生成不同的ConcreteProduct,当然这些ConcreteProduct都是继承自AbstractProduct的。
  • 抽象产品类AbstractProduct:抽象产品是从其他具体产品抽象出来的。抽象产品类只有一个。
  • 具体产品类ConcreteProduct:具体产品类继承自抽象产品类,可以有多个。当需要增加新的产品的时候就增加一个继承自抽象产品类的具体产品类即可。

二 优势
实现了松耦合,当需要增加一种新产品(在大话设计模式中,例子是运算Operation),只需要做两点改动:

  • 增加一个继承自抽象产品(抽象的运算)的具体产品(一种具体的运算);
  • 在工厂类中,switch中,增加一种根据标识符产生新运算的case即可。

三 C++代码实现
开发环境 Visual Studio Community 2017

#include "pch.h"
#include <iostream>
#include <string>
using namespace std;
//抽象的产品类
class Operation
{
public:
	double GetNumberA() const
	{
		return this->numberA;
	}
	double GetNumberB() const
	{
		return this->numberB;
	}
	void SetNumberA(const double A)
	{
		this->numberA = A;
	}
	void SetNumberB(const double B)
	{
		this->numberB = B;
	}
	virtual double GetResult()
	{
		double result = 0;
		return result;
	}
protected:
	double numberA;
	double numberB;
};
//下面是四种具体产品类
class OperationAdd : public Operation
{
public:
	double GetResult()
	{
		double result = 0;
		result = this->numberA + this->numberB;
		return result;
	}
};

class OperationSub : public Operation
{
public:
	double GetResult()
	{
		double result = 0;
		result = this->numberA - this->numberB;
		return result;
	}
};


class OperationMul : public Operation
{
public:
	double GetResult()
	{
		double result = 0;
		result = this->numberA * this->numberB;
		return result;
	}
};

class OperationDiv : public Operation
{
public:
	double GetResult()
	{
		double result = 0;
		if (numberB != 0)
		{
			result = this->numberA / this->numberB;
		}		
		return result;
	}
};
//到底要实例化谁,将来会不会增加实例化操作,比如增加开根运算
//应该考虑用一个单独的类来做这个创造实例的过程,这就是工厂
class OperationFactory
{
public:
	static Operation* createOperate(char type)
	{
		Operation* oper = NULL;
		switch (type)
		{
		case '+':
			oper = new OperationAdd();
			break;
		case '-':
			oper = new OperationSub();
			break;
		case '*':
			oper = new OperationMul();
			break;
		case '/':
			oper = new OperationDiv();
			break;
		default:
			break;
		}
		return oper;
	}


};
//客户端代码
int main()
{
	Operation* oper;
	double strNumberA;
	double strNumberB;
	char type;
	cout << "请输入数字A" << endl;
	cin >> strNumberA;
	cout << "请输入数字B" << endl;
	cin >> strNumberB;
	cout << "请选择运算符号" << endl;
	cin >> type;
	oper = OperationFactory::createOperate(type);
	oper->SetNumberA(strNumberA);
	oper->SetNumberB(strNumberB);
	cout << oper->GetResult() << endl;
	if (oper != NULL)
	{
		delete oper;
		oper = NULL;
	}
    
	return 0;
}

原文地址:https://www.cnblogs.com/Manual-Linux/p/11099795.html