说简单工厂模式时,我们讲到,如果需要添加一个乘法运算符应该怎么做的问题,解决这个问题,需要用到工厂方法模式。
工厂方法模式,定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类,结构图如下
代码实现如下
#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;
}
这样的话,你只需要在客户端修改就可以了。