工厂方法模式
1. 简单工厂模式:
class operFactory
{
public:
static Operation *createOperation(char c)
{
switch(c)
{
case '+':
return new addOperation;
break;
case '-':
return new subOperation;
break;
case '*':
return new mulOperation;
break;
case '/':
return new divOperation;
break;
}
}
};
int main()
{
Operation *oper=operFactory::createOperation('+');
oper->numberA=9;
oper->numberB=99;
cout<<oper->getResult()<<endl;
return 0;
}
2. 工厂方法模式实现计算器:
class IFactory
{
public:
virtual Operation *createOperation()=0;
};
class AddFactory:public IFactory
{
public:
static Operation *createOperation()
{
return new addOperation();
}
};
class SubFactory:public IFactory
{
public:
static Operation *createOperation()
{
return new subOperation();
}
};
class MulFactory:public IFactory
{
public:
static Operation *createOperation()
{
return new mulOperation();
}
};
class DivFactory:public IFactory
{
public:
static Operation *createOperation()
{
return new divOperation();
}
};
3.简单工厂vs工厂方法:
简单工厂模式最大的优点在于,工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖。比如计算器,客户端不用管该用哪个类的实例,只需要吧“+”给工厂,工厂自动给出相应实例,客户端只要做运算就可以了。
工厂方法模式,定义一个用于创建对象的接口,让子类决定实例化哪一个类。
工厂方法模式实现时,客户端需要决定实例化哪一个工厂来实现运算类。
int main()
{
Operation *oper=MulFactory::createOperation();
oper->numberA=9;
oper->numberB=99;
cout<<oper->getResult()<<endl;
return 0;
}