设计模式 之 简单工厂模式

简单工厂模式

简单工厂模式是属于设计模式中的创建性模式,一般是使用静态方法,通过接收不同的参数,返回不同类型的对象实例,下面以大话设计模式中的计算器来举例。计算器一般常见的是四种运算法则,加减乘除。客户端传入需要运算的符号时,会返回该运算的对象实例,进行相应的计算。扩展性较差,添加一个新的运算法则需要修改工厂类Factory,下面是计算器的类图。

下面来看看具体的代码:

/***计算器**简单的工厂类**/

#include <iostream>
#include <string>
using namespace std;

enum OPER_TYPE{
	OPER_NULL = -1,
	OPER_ADD =0,
	OPERA_MINS,
	OPERA_MUL,
	OPERA_DIV
};

class Operation{  //定义一个基类对象
	public:
		Operation(){
			m_num1 = 0.0;
			m_num2 = 0.0;
		}
		virtual ~Operation(){
		}
		void setNum(double num1,double num2){
			m_num1 = num1;
			m_num2 = num2;
		}
		virtual double GetResult() =0;
	public:
		int m_num1;
		int m_num2;
};

class  AddOpera:public Operation{
	public:
		double GetResult()
		{
			return m_num1 + m_num2;
		}
};
class  MinsOpera:public Operation{
	public:
		double GetResult()
		{
			return m_num1 - m_num2;
		}
		
};
class  MulOpera:public Operation{
	public:
		double GetResult()
		{
			return m_num1 * m_num2*1.0;
		}
};
class  DivOpera:public Operation{
	public:
		double GetResult(){
			if(m_num2 ==0)
			{
				cout << " it is must not 0" << endl;
				return 0;
			}
			else 
			{
				return m_num1/m_num2;
			}
		}
};
class Factory{
	
    public:
		Factory(){
			oper = NULL;
		}
	public:
		void CreateFactor(string op){
			
			switch(get_oper_type(op)){
				case OPER_ADD:
					oper = new AddOpera();
					break;
				case OPERA_MINS:
					oper = new MinsOpera();
					break;
				case OPERA_MUL:
					oper = new MulOpera();
					break;
				case OPERA_DIV:
					oper = new DivOpera();
					break;
				default:
					cout <<"** input is error ***" << endl;
			}
		}
		OPER_TYPE get_oper_type(string op){
			if(op =="+"){
				return OPER_ADD;
			}
			else if(op == "-"){
				return OPERA_MINS;
			}
			else if(op == "*"){
				return OPERA_MUL;
			}
			else if(op == "/"){
				return OPERA_DIV;
			}
			else{
				return OPER_NULL;
			}
		}
		Operation* GetType(){
			return oper;
		}
	private:
		Operation* oper;
};

int main()
{
	Factory fac;
	fac.CreateFactor("*");
	Operation* oper1 = fac.GetType();
	oper1->setNum(1.3,3.0);
	double result = oper1->GetResult();
	cout << "***the last result is :" << result << endl;
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值