首页 > 代码库 > 设计模式(1)--简单工厂模式

设计模式(1)--简单工厂模式

//ver1
class Operation
{
public:
	static double GetResult(double A, double B, char operate)
	{
		double result = 0;
		switch(operate)
		{
		case ‘+‘:
			result = A + B;
			break;
		case ‘-‘:
			result = A - B;
			break;
		default:
			break;
		}
		return result;
	}
};

void main1()
{
	double A = 1.1;
	double B = 2.2;
	char oper = ‘+‘;
	double result = Operation::GetResult(A, B, oper);	
}

 

//ver2
class Operation
{
public:
	Operation(){}
	~Operation(){}
protected:
	double _NumberA;
	double _NumberB;
public:
	void SetNumberA(double A)
	{
		_NumberA = A;
	}
	double GetNumberA()
	{
		return _NumberA;
	}
	void SetNumberB(double B)
	{
		_NumberB = B;
	}
	double GetNumberB()
	{
		return _NumberB;
	}

	virtual double GetResult()
	{
		double result = 0;
		return result;
	}
};

class OperationAdd : public Operation
{
public:
	virtual double GetResult()
	{
		double result = _NumberA + _NumberB;
		return result;
	}
};

class OperationSub : public Operation
{
public:
	virtual double GetResult()
	{
		double result = _NumberA - _NumberB;
		return result;
	}
};

//工厂
class OperationFactory
{
public:
	static Operation CreateOperate(char operate)
	{
		Operation *oper = NULL;
		switch(operate)
		{
		case ‘+‘:
			oper = new OperationAdd();
			break;
		case ‘-‘:
			oper = new OperationSub();
			break;
		default:
			break;
		}
		return *oper;
	}
};

void main2()
{
	Operation oper;
	oper = OperationFactory::CreateOperate(‘+‘);
	oper.SetNumberA(1.1);
	oper.SetNumberB(2.2);
	double result = oper.GetResult();
}

  

 

设计模式(1)--简单工厂模式