简单工厂模式又被称为静态工厂模式。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。简单工厂模式是工厂模式家族中最简单实用的模式,可以理解为是不同工厂模式的一个特殊实现。
UML类图:
类图中只列出主要方法,而只有工厂类中给出了构造和析构函数,并且都是私有。目的是强调这个工厂类的作用只是“出产品”,自己不需要实例化,所以将构造和析构声明为私有(这个只适用于“简单”工厂模式)。
代码(为减小篇幅,代码只实现部分,并code到一个cpp文件中):
1
#include <iostream>
2
3
using namespace std;
4
5
/**//// @brief Base operation class. 6
class Operation
7

{
8
protected:
9
double m_numA;
10
double m_numB;
11
12
public:
13
Operation(): m_numA(0.0), m_numB(0.0)
{
14
cout << "Operation constructor" << endl;
15
}
16
17
virtual ~Operation()
{
18
cout << "Operation destructor" << endl;
19
}
20
21
double virtual getResult() = 0;
22
};
23
24
/**//// @brief The class implement the add operation.25
class OperAdd: public Operation
26

{
27
public:
28
OperAdd(double a, double b)
{
29
cout << "OperAdd constructor" << endl;
30
m_numA = a;
31
m_numB = b;
32
}
33
34
~OperAdd()
{
35
cout << "OperAdd destructor" << endl;
36
}
37
38
double getResult()
{
39
return (m_numA + m_numB);
40
}
41
};
42
43
/**//// @brief The class OperSub, OperMul and OperDiv omitted. 44
45
class OperFactory
46

{
47
public:
48
enum OPER_TYPE
{
49
ADD = 1,
50
SUB = 2,
51
MUL = 3,
52
DIV = 4
53
};
54
55
static Operation* createOperation(OPER_TYPE oper, double a, double b);
56
};
57
58
Operation* OperFactory::createOperation(OPER_TYPE oper, double a, double b)
59

{
60
Operation* pOper = NULL;
61
62
switch (oper)
{
63
case ADD:
64
pOper = new OperAdd(a, b);
65
break;
66
default:
67
break;
68
}
69
70
return pOper;
71
}
72
73
int main()
74

{
75
Operation* pOper = OperFactory::createOperation(OperFactory::ADD, 2.1, 3.3);
76
77
if (pOper)
{
78
cout << pOper->getResult() << endl;
79
80
delete pOper;
81
pOper = NULL;
82
}
83
84
return 0;
85
}
简单工厂模式的最大优点在于工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖。但简单工厂模式的工厂类是开放的,如果要增加其它产品,则要修改工厂类,这一点违背开放-封闭原则(Open-Close Principle,对扩展开发,对修改关闭)。而要克服这一缺点,则要使用工厂方法模式(Factory Method),这种经过改进工厂模式将在下一节介绍。