简单工厂模式

简单工厂模式

定义

简单工厂模式(Simple Factory Pattern):又称为静态工厂方法(Static Factory Method)模式,它属于类创建型模式。在简单工厂模式中,可以根据参数的不同返回不同类的实例。简单工厂模式专门定义一个类来负责创建其他类的实例,被创建类的实例通常具有共同的父类。

例子(已测试)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <iostream>

using namespace std;

typedef enum ProductTypeTa
{
TypeA,
TypeB,
TypeC
} PRODUCTTYPE;

class Product
{
public:
virtual void print() = 0;
};

class ProductA : public Product
{
public:
virtual void print()
{
cout << "This is product A" << endl;
}
};

class ProductB : public Product
{
public:
virtual void print()
{
cout << "This is product B" << endl;
}
};

class ProductC : public Product
{
public:
virtual void print()
{
cout << "This is product C" << endl;
}
};

class Factory
{
public:
Product *create_product(PRODUCTTYPE type)
{
switch (type)
{
case TypeA:
return new ProductA();
case TypeB:
return new ProductB();
case TypeC:
return new ProductC();
default:
return NULL;
}
}
};

int main(void)
{

Factory *productFactory = new Factory();
Product *productObjA = productFactory->create_product(TypeA);
if (productObjA != NULL)
{
productObjA->print();
}
Product *productObjB = productFactory->create_product(TypeB);
if (productObjB != NULL)
{
productObjB->print();
}
Product *productObjC = productFactory->create_product(TypeC);
if (productObjC != NULL)
{
productObjC->print();
}
delete productFactory;
productFactory = NULL;
delete productObjA;
productObjA = NULL;
delete productObjB;
productObjB = NULL;
delete productObjC;
productObjC = NULL;
return 0;
}

输出:

This is product A
This is product B
This is product C

总结

  • 优点:实现对象的创建和使用分离,创建完全交给专门的工厂类去负责,程序员不需要关心对象是如何创建出来的,只用关心如何使用即可

  • 缺点:不够灵活,在本例中,如果新增一个产品类,就要修改工厂类,修改其判断逻辑。违反了开闭原则,没有办法做到灵活扩展

  • 感想:其实简单工厂模式就是一种分类讨论的思想,根据用户需求的不同生成不同的对象,将这个分类讨论的逻辑放在工厂类里面,最终生成特定类型的对象