工厂模式,顾名思义,这种模式的工作方式类似于工厂。工厂包含多个车间,各个车间生产不同的产品,客户向工厂提交不同的需求,工厂都能根据客户的需求提交产品。
模式定义
简单工厂模式:又称为静态工厂方法(Static Factory Method)模式,它属于类创建型模式。在简单工厂模式中,可以通过一个类(工厂类)来管理产品的生产,工厂类向实际生产者们传达客户的需求(传入的参数),当生产者们接收到需求(参数),则根据需求生产对应的产品,再返回。
简单工厂模式专门定义一个类(职责:管理)来负责创建其他类的实例,被创建的实例通常都具有共同的父类,被创建的类就相当于工厂中的各个车间。
UML图:
参考代码:
/*
工厂模式
*/
#ifndef _FACTORY_
#define _FACTORY_
//抽象基类 : 算术类。其中,加法和乘法都有一个共性,都属于算术方法。
class Arithmetic
{
public:
virtual double GetResult(double x, double y) = 0;
};
//具体子类 : 加法
class Add : public Arithmetic
{
public:
virtual double GetResult(double x, double y)
{
return x + y;
}
};
// 具体子类:乘法
class Mul : public Arithmetic
{
public:
virtual double GetResult(double x, double y)
{
return x * y;
}
};
/*
工厂类,根据type来选择生成不同的实例
由于GetResult是虚方法,基类指针将根据对象实际类型调用方法
*/
class Factory
{
public:
static Arithmetic * Production(int type)
{
switch (type)
{
case 1:
return new Add();
case 2:
return new Mul();
default:
break;
}
}
};
#endif // _FACTORY_
测试代码:
#include "Factory.h"
#include <iostream>
using namespace std;
int main()
{
Arithmetic * product = Factory::Production(1);
cout<< product->GetResult(3,3) <<endl; //结果为3+3=6
product = Factory::Production(2);
cout<< product->GetResult(3,3) <<endl; //结果为3*3=9
return 0;
}
小结
工厂模式是一个创建型模式,易于扩展和维护。如上述例子,当需要再增加一种算法(除法)时,只需要通过继承和重写虚方法GetResult(),便能在不修改原有代码的基础上达到目的。经常修改原有代码可能会导致意想不到的结果,试想一下,如果某次不经意的修改导致在Add::GetResult()中开头直接return 0;
,那么在其他引用了该算法的地方都将可能出错。