工厂模式--大话设计模式

参考《大话设计模式》

工厂方法:定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法模式使一个类的实例化延迟到其子类;


factory.h

#ifndef _FACTORY_H_
#define _FACTORY_H_

class Operation;    //前向声明
class CFactory
{
public:
	CFactory()              {}
	virtual ~CFactory()     {}
	virtual Operation* CreateOperation() {return NULL;}
};
#endif

factory_add.h

#ifndef _FACTORY_ADD_H_
#define _FACTORY_ADD_H_

#include "factory.h"
#include "operation_add.h"

class CFactoryAdd : public CFactory
{
public:
	CFactoryAdd()              {}
	virtual ~CFactoryAdd()     {}
	virtual Operation* CreateOperation()
	{
		return new OperationAdd;
	}
};
#endif

factory_sub.h

#ifndef _FACTORY_SUB_H_
#define _FACTORY_SUB_H_

#include "factory.h"
#include "operation_sub.h"

class CFactorySub:public CFactory
{
public:
	CFactorySub()              {}
	virtual ~CFactorySub()     {}
	virtual Operation* CreateOperation()
	{
		return new OperationSub;
	}
};
#endif

operation.h

#ifndef _OPERATION_H_
#define _OPERATION_H_

class Operation
{
public:
	Operation() {}
	Operation(double num1,double num2)
		:num1_(num1)
		,num2_(num2_)
	{

	}
	virtual ~Operation() {}
	virtual double GetResult() { return 0;      }
	double get_num2() const    { return num2_;  }
	void set_num2(double val)  { num2_ = val;   }
	double get_num1() const    { return num1_;  }
	void set_num1(double val)  { num1_ = val;   }
protected:
	double num1_;
	double num2_;
	
};
#endif

operation_add.h

#ifndef _OPERATION_ADD_H_
#define _OPERATION_ADD_H_

#include "operation.h"

class OperationAdd: public Operation
{
public:
	OperationAdd() {}
	virtual ~OperationAdd() {}
	virtual double GetResult() { return num1_ + num2_; }
};

#endif

operation_sub.h

#ifndef _OPERATION_SUB_H_
#define _OPERATION_SUB_H_

#include "operation.h"

class OperationSub: public Operation
{
public:
	OperationSub() {}
	virtual ~OperationSub() {}
	virtual double GetResult() { return num1_ - num2_; }
};

#endif

main.cpp

#include <iostream>
#include "factory_add.h"
#include "factory_div.h"
#include "factory_mul.h"
#include "factory_sub.h"
#include "Operation.h"

int main()
{
    CFactory *factory_add = new CFactoryAdd;
	Operation * oper = factory_add->CreateOperation();
	oper->set_num1(56);
	oper->set_num2(54);
	std::cout<<oper->GetResult()<<std::endl;
	delete factory_add;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值