1.工厂方法模式简介
-
英文名称
Factory Method -
主要目的
定义一个用来创建对象的接口,从而让其子类来决定实例化哪一个类。工厂方法能使一个类的实例化行为,延迟到其子类中进行。 -
使用场景
1.当一个类不知道它所必须创建的对象的类的时候;
2.当一个类希望由它的子类来指定它所创建的对象的时候。
2.工厂方法代码示例
-
测试平台
1.开发语言:C++
2.开发工具:VS2015
3.操作系统:Win7 X64 -
代码说明
1.Operator–抽象操作类,定义功能接口;
2.OperatorAdd、OperatorSub–具体操作类,实现操作接口;
3.AFactory–抽象工厂类,定义抽象工厂创建接口;
4.AddFactory、SubFactory–具体工厂类,用于创建具体的操作类。 - 具体代码
#include <iostream>
using namespace std;
//抽象操作类
class Operator
{
public:
virtual int Operate(int val1, int val2) = 0; //抽象计算接口
};
//加法类
class OperatorAdd:public Operator
{
public:
int Operate(int val1, int val2) //计算接口
{
return val1 + val2;
}
};
//减法类
class OperatorSub :public Operator
{
public:
int Operate(int val1, int val2) //计算接口
{
return val1 - val2;
}
};
//抽象工厂类
class AFactory
{
public:
virtual Operator* CreateOperation()=0; //抽象创建工厂接口
};
//加法工厂类
class AddFactory:public AFactory
{
public:
Operator* CreateOperation() //创建工厂接口
{
Operator* pOperator = new OperatorAdd();
return pOperator;
}
};
//减法工厂类
class SubFactory :public AFactory
{
public:
Operator* CreateOperation() //创建工厂接口
{
Operator* pOperator = new OperatorSub();
return pOperator;
}
};
int main()
{
int val1 = 5, val2 = 4;
//加法操作
AFactory* pOperaFactory1 = new AddFactory();
if (NULL!=pOperaFactory1)
{
Operator* pOper1 = pOperaFactory1->CreateOperation();
if (NULL!= pOper1)
{
int ret = pOper1->Operate(val1, val2);
cout << val1 << "+" << val2 << "=" << ret << endl;
delete pOper1;
pOper1 = NULL;
}
delete pOperaFactory1;
pOperaFactory1 = NULL;
}
//减法操作
AFactory* pOperaFactory2 = new SubFactory();
if (NULL != pOperaFactory2)
{
Operator* pOper2 = pOperaFactory2->CreateOperation();
if (NULL != pOper2)
{
int ret = pOper2->Operate(val1, val2);
cout << val1 << "-" << val2 << "=" << ret << endl;
delete pOper2;
pOper2 = NULL;
}
delete pOperaFactory2;
pOperaFactory2 = NULL;
}
getchar();
return 0;
}
-
输出结果
栏目导航
上一篇:设计模式–设计模式简介和分类(一)
下一篇:设计模式–抽象工厂模式(三)
参考文献:
1.《设计模式:可复用面向对象软件的基础》