工厂方法模式 C++描述

说简单工厂模式时,我们讲到,如果需要添加一个乘法运算符应该怎么做的问题,解决这个问题,需要用到工厂方法模式。

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

 

代码实现如下

#include<iostream>
using namespace std;
class Product
{
public:
	virtual void operation()=0;
};
class Creator
{
public:
	virtual Product* FactoryMethod()=0;
};

class ConcreteProduct:public Product
{
public:
	void operation()
	{
		cout<<"ConcreteProduct::operation()"<<endl;
	}
};

class ConcreteCreator:public Creator
{
public:
	Product* FactoryMethod()
	{
		return new ConcreteProduct;
	}
};
int main()
{
    Creator* creator=new ConcreteCreator();
    Product* product=creator->FactoryMethod();
    product->operation();
    delete product;
    delete creator;
}
现在再想想之前提出的问题,加法类,减法类,乘法类都是继承Operation(相当于Product),我们需要新建一个抽象工厂类(相当于Creator),然后依次为加法类、减法类、乘法类,生成工厂类。
#include<iostream>
using namespace std;

class Operation
{
public:
	Operation(int numA,int numB)
	{
		numberA=numA;
		numberB=numB;
	}
	int GetNumberA()	{		return numberA;	}
	int GetNumberB()	{		return numberB;	}
	virtual int GetResult()=0;          //让子类去实现这个纯虚函数,不同的运算符实现不同的操作结果
private:
	int numberA;
	int numberB;
};

class OperationAdd:public Operation
{
public:
	OperationAdd(int numA,int numB):Operation(numA,numB){}
	int GetResult()
	{
		int result=GetNumberA()+GetNumberB();
		return result;
	}
};

class OperationSub:public Operation
{
public:
	OperationSub(int numA,int numB):Operation(numA,numB){}
	int GetResult()
	{
		int result=GetNumberA()-GetNumberB();
		return result;
	}
};

class OperationMul:public Operation
{
public:
	OperationMul(int numA,int numB):Operation(numA,numB){}
	int GetResult()
	{
		int result=GetNumberA()*GetNumberB();
		return result;
	}
};

class OperationFactory
{
public:
	virtual Operation* CreateOperation(int,int)=0;
};

class AddFactory:public OperationFactory
{
public:
	Operation* CreateOperation(int numA,int numB){		return new OperationAdd(numA,numB);	}
};

class SubFactory:public OperationFactory
{
public:
	Operation* CreateOperation(int numA,int numB){		return new OperationSub(numA,numB);	}
};

class MulFactory:public OperationFactory
{
public:
	Operation* CreateOperation(int numA,int numB){		return new OperationMul(numA,numB);	}
};


int main()
{
	OperationFactory* fac=new AddFactory();
	Operation* operation=fac->CreateOperation(1,2);
	cout<<operation->GetResult()<<endl;
	delete operation;
	delete fac;
}
这样的话,你只需要在客户端修改就可以了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值