首页 > 代码库 > 大话设计模式C++实现一:简单工厂模式

大话设计模式C++实现一:简单工厂模式

#include <iostream>
#include <cstdlib>

using namespace std;

class Operation
{
protected:
	double numberA;
	double numberB;
public:
	double getA()
	{
		return numberA;
	}
	double getB()
	{
		return numberB;
	}
	void setA(double number)
	{
		numberA = number;
	}
	void setB(double number)
	{
		numberB = number;
	}
	virtual double GetResult()
	{
		double result = 0;
		return result;
	}
};
class operationAdd :public Operation
{
public:
	double GetResult()
	{
		double result = 0;
		result = numberA + numberB;
		return result;
	}
};
class operationSub :public Operation
{
public:
	double GetResult()
	{
		double result = 0;
		result = numberA - numberB;
		return result;
	}
};
class operationMul :public Operation
{
public:
	double GetResult()
	{
		double result = 0;
		result = numberA * numberB;
		return result;
	}
};
class operationDiv :public Operation
{
public:
	double GetResult()
	{
		double result = 0;
		result = numberA / numberB;
		return result;
	}
};

class OperationFactory
{
public:
	Operation* createOperation(char type)
	{
		Operation *oper;
		switch (type)
		{
		case ‘+‘:
			oper = new operationAdd;
			break;
		case ‘-‘:
			oper = new operationSub;
			break;
		case ‘*‘:
			oper = new operationMul;
			break;
		case ‘/‘:
			oper = new operationDiv;
			break;
		}
		return oper;
	}
};
int main()
{
	Operation* oper = NULL;
	OperationFactory of;
	double A;
	double B;
	char op;
	cout << "Input A:";
	cin >> A;
	cout << "Input B:";
	cin >> B;
	cout << "Input oper:";
	cin >> op;
	oper = of.createOperation(op);
	oper->setA(A);
	oper->setB(B);
	cout << oper->GetResult() << endl;
	if (oper != NULL)
	{
		delete oper;
		oper = NULL;
	}
	return 0;
}

  

大话设计模式C++实现一:简单工厂模式