代码改变世界

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

2016-10-31 23:59  sylar_liang  阅读(190)  评论(0编辑  收藏  举报
//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();
}