参考大话设计模式中的工厂方法模式
/*
* factory_method.cpp
*
* Created on: Jul 21, 2017
* Author: clh01s@163.com
*/
#include <iostream>
using namespace std;
//基础操作类,加法类,减法类,乘法类,除法类的父类
class Operation
{
public:
virtual ~Operation(){}
double get_num_a(){return _number_a;}
double get_num_b(){return _number_b;}
void set_num_a(double a){_number_a = a;}
void set_num_b(double b){_number_b = b;}
//虚函数
virtual double GetResult()
{
double result = 0;
return result;
}
private:
double _number_a;
double _number_b;
};
//工厂接口
class IFactory
{
public:
virtual ~IFactory(){}
virtual Operation *CreateOperation()
{
return CreateOperation();
}
};
//加法类
class OperationAdd:public Operation
{
public:
//重写虚函数GetResult
double GetResult() override
{
double result = get_num_a() + get_num_b();
return result;
}
};
//减法类
class OperationSub:public Operation
{
public:
//重写虚函数GetResult
double GetResult() override
{
double result = get_num_a() - get_num_b();
return result;
}
};
//乘法类
class OperationMul:public Operation
{
public:
//重写虚函数GetResult
double GetResult() override
{
double result = get_num_a() * get_num_b();
return result;
}
};
class OperationDiv:public Operation
{
public:
//重写虚函数GetResult
double GetResult() override
{
if(0 == get_num_b())
{
//除数不能为0
return -1;
}
double result = get_num_a() / get_num_b();
return result;
}
};
//建立具体工厂实现各个接口
//返回各自操作的指针
class AddFactory :public IFactory
{
public:
Operation *CreateOperation() override
{
return new OperationAdd();
}
};
class SubFactory :public IFactory
{
public:
Operation *CreateOperation() override
{
return new OperationSub();
}
};
class MulFactory :public IFactory
{
public:
Operation *CreateOperation() override
{
return new OperationMul();
}
};
class DivFactory :public IFactory
{
public:
Operation *CreateOperation() override
{
return new OperationDiv();
}
};
int main()
{
IFactory *operFactory = new AddFactory();
Operation *oper = operFactory->CreateOperation();
oper->set_num_a(12.51);
oper->set_num_b(123.234);
cout<<"工厂方法获得的答案是:"<<oper->GetResult()<<endl;
return 0;
}
工厂方法模式解决的问题是(摘录自《设计模式》):
在一个应用框架中两个主要的抽象类是Application和Document因为这两个类都是抽象的,客户必须通过他们的子类来做相关的应用和实现,且Application负责管理Document.因为被实例化的Document子类是与特定应用相关的,所以Application的类不可能知道哪一个Document子类将被创建.这就产生一个尴尬的局面:框架必须实例化类,但是它只知道不能被实例化的抽象类.
factory method 模式提供了一个解决方案.它封装了哪一个特定子类将被创建的信息并将这些信息从框架中分离出来.
Application的子类重新定义Application的抽象操作CreateDocument以返回适当的Document子类对象.一旦一个Application子类实例化以后,它就可以实例化与应用相关的文档,而无需知道这些文档的类.
工厂方法模式优点:
工厂方法不再将与特定应用有关的类绑定到你的代码中.代码仅处理Product接口.因此它可以与用户定义的任何ConcreteProduct类一起使用.
缺点:
客户可能仅仅为了创建一个特定的ConcreteProduct对象就不得不创建Creator的子类.当Creator子类不必须时,客户现在必然要处理类演化的其他方面.
转载请标明源地址:http://blog.csdn.net/clh01s/article/details/75646045