简单工厂模式又称静态工厂方法模式(Static Factory Method),它不是23种模式之一,但是却是我们常用的设计模式之一。代码先行:
1: // abstract base class2: class Operation3: {
4: public:5: int m_nFirst;6: int m_nSecond;7:
8: virtual double GetResult() = 0;9:
10: virtual ~Operation()11: {
12:
13: }
14: };
15:
16: // AddOperation class, Operation's child17: class AddOperation: public Operation18: {
19: double GetResult()20: {
21: return m_nFirst + m_nSecond;22: }
23: };
24:
25: // SubOperation class, Operation's child26: class SubOperation: public Operation27: {
28: double GetResult()29: {
30: return m_nFirst - m_nSecond;31: }
32: };
33:
34: // Factory class35: class SimpleFactory36: {
37: public:38: static Operation* CreateOperation(const char a);39: };
40:
41: Operation* SimpleFactory::CreateOperation(const char a)42: {
43: switch(a)44: {
45: case '+':46: return new AddOperation;47:
48: case '-':49: return new SubOperation;50:
51: }
52: }
简单解析:在上面的代码中有四个类:Operation、AddOperation、SubOperation和SimpleFactory。AddOperation和SubOperation是Operation的子类,继承了Operation的两个数据成员和GetResult()方法,一个是加法操作,一个是减法操作。SimpleFactory是简单工厂模式的核心,它负责根据用户传递的信息来创建具体的对象,进而在多态的支持下实现程序预想的功能。
客户端用户需要知道基类Operation和工厂类来创建相应的对象并调用对应的方法,耦合性不算好。
客户代码示例:
1: #include <iostream>2: #include "simpleFactory.h"3:
4: using namespace std;5:
6: int main(int argc, char* argv[])7: {
8: // client code9: Operation* op = NULL;
10:
11: op = SimpleFactory::CreateOperation('+');12: op->m_nFirst = 4;
13: op->m_nSecond = 5;
14: int sum = op->GetResult();15: delete op; // don't forget to delete16: op = NULL;
17: cout<<"sum is:"<<sum<<endl;18:
19: op = SimpleFactory::CreateOperation('-');20: op->m_nFirst = 4;
21: op->m_nSecond = 5;
22: int sub = op->GetResult();23: delete op;24: op = NULL;
25: cout<<"sub is:"<<sub<<endl;26:
27: return 0;28: }
上面示例代码的输出如下:
1: sum is:9
2: sub is:-1
模式的本质:新添加类时,不会影响以前的系统代码。核心思想是用一个工厂来根据输入的条件产生不同的类,然后根据不同类的virtual函数得到不同的结果。