首页 > 代码库 > <C/C++ 版> 设计模式 学习之 工厂模式 <2>

<C/C++ 版> 设计模式 学习之 工厂模式 <2>

下面代码实现的功能是简单工厂模式:

声明一个工厂类,其成员可以看做该工厂的主要产品类型。

再声明几个子工厂类,根据客户要求生产不同类型的产品。

若要增加新产品,只需声明新的工厂子类即可。

代码如下:

//Factory.h

#ifndef FACTORY_H
#define FACTORY_H

//计算类
class COperate
{
public:
	COperate(void);
	COperate(float num_a, float num_b);
	virtual float GetResult();	

public:
	static float number_a;
	static float number_b;
};

//计算子类--加
class COperate_Add:public COperate
{
public:
	virtual float GetResult();
};

//计算子类--减
class COperate_Sub:public COperate
{
public:
	virtual float GetResult();
};

//计算子类--乘
class COperate_Mul:public COperate
{
public:
	virtual float GetResult();
};

//计算子类--除
class COperate_Div:public COperate
{
public:
	virtual float GetResult();
};

//计算工厂类
class COperateFactory
{
public:
	static COperate * CreateOperate(char operate_sign);
};

#endif



//Factory.cpp

#include "Factory.h"

float COperate::number_a = 0;
float COperate::number_b = 0;

//默认的构造函数
COperate::COperate(void)
{
	//number_a = 0;
	//number_b = 0;
}

COperate::COperate(float num_a, float num_b)
{
	number_a = num_a;
	number_b = num_b;
}

float COperate::GetResult()
{
	float result = 0;
	return result;
}

//计算子类
float COperate_Add::GetResult()
{
	float result = 0;
	result = number_a + number_b;
	return result;
};

float COperate_Sub::GetResult()
{
	float result = 0;
	result = number_a - number_b;
	return result;
	
};

float COperate_Mul::GetResult()
{
	float result = 0;
	result = number_a * number_b;
	return result;
};

float COperate_Div::GetResult()
{
	float result = 0;
	result = number_a / number_b;
	return result;
};

COperate * COperateFactory::CreateOperate(char operate_sign)
{
	COperate * ope = 0;

	switch(operate_sign)
	{
	case '+':
		{
			ope = new COperate_Add;
			break;
		}
	case '-':
		{			
			ope = new COperate_Sub;
			break;
		}
	case '*':
		{
			ope = new COperate_Mul;
			break;
		}
	case '/':
		{
			ope = new COperate_Div;
			break;
		}
	}

	return ope;
}



//User.cpp --- 客户端

#include "Factory.h"
#include "iostream"

int main()
{
	using namespace std;
	
	float num_a, num_b;
	char ope_sign;

	cout<<"Input First Number : ";
	cin>>num_a;

	cout<<"Input Second Number : ";
	cin>>num_b;

	cout<<"Input Operate sign : ";
	cin>>ope_sign;
	
	COperate * myOpera = new COperate(num_a, num_b);
	myOpera = COperateFactory::CreateOperate(ope_sign);
	float result = myOpera->GetResult();

	cout<<"Result is : "<<result<<endl;
}


<C/C++ 版> 设计模式 学习之 工厂模式 <2>