您的位置:首页 > 编程语言 > C语言/C++

大话设计模式--工厂模式 factory -- C++实现实例

2013-10-07 15:53 741 查看
实现《大话设计模式》的C++版本。。。

1. 工厂模式 使用的范围是 同一个基类,下面很多子类。

(1)这里很容易出现的一个问题n多的子类继承自抽象基类,我们不得不在每次要用到子类的地方就编写诸如new ×××;的代码。这里带来两个问题1)客户程序员必须知道实际子类的名称(当系统复杂后,命名将是一个很不好处理的问题,为了处理可能的名字冲突,有的命名可能并不是具有很好的可读性和可记忆性,就姑且不论不同程序员千奇百怪的个人偏好了。),2)程序的扩展性和维护变得越来越困难。

(2)还有一种情况就是在父类中并不知道具体要实例化哪一个具体的子类。这里的意思为:假设我们在类A中要使用到类B,B是一个抽象父类,在A中并不知道具体要实例化那一个B的子类,但是在类A的子类D中是可以知道的。在A中我们没有办法直接使用类似于new ×××的语句,因为根本就不知道×××是什么。

注意: 如下的结构图, 假设还要添加一个算法, 则需要多实现一个算法类, 并且修改简单工厂类的case,这违反 “开放--封闭”原则, 对扩展开放,对修改封闭。。。

这是工厂模式的缺点,后文有工厂方法模式的比较。。

下面为(1)的示例:一个关于计算器的设计, 设计有 “+ - * /”等运算,基类 operation , 下面有“+ - * /”的实现子类。



operation.h

#ifndef OPERATION_H
#define OPERATION_H

class operation
{
public:
operation();
double virtual getResult();

double strA;
double strB;
double result;
};

#endif // OPERATION_H

operation.cpp

#include "operation.h"

operation::operation()
{
strA = 0;
strB = 0;
result = 0;
}

double operation::getResult()
{
return result;
}


operationFunc.h

#ifndef OPERATIONFUNC_H
#define OPERATIONFUNC_H

#include "operation.h"

class OperationAdd : public operation
{
public:
double getResult();
};

class OperationSub : public operation
{
public:
double getResult();
};

class OperationMul : public operation
{
public:
double getResult();
};

class OperationDiv : public operation
{
public:
double getResult();
};

#endif // OPERATIONFUNC_H

operationFunc.cpp

#include "operationFunc.h"

double OperationAdd::getResult()
{
result = strA + strB;
return result;
}

double OperationSub::getResult()
{
result = strA - strB;
return result;
}

double OperationMul::getResult()
{
result = strA * strB;
return result;
}

double OperationDiv::getResult()
{
result = strA / strB;
return result;
}


operationfactory.h

#ifndef OPERATIONFACTORY_H
#define OPERATIONFACTORY_H

#include <string>
#include "operation.h"
#include "operationFunc.h"
using namespace std;

class OperationFactory
{
public:
OperationFactory();
operation* createOperation(string operStr);
};

#endif // OPERATIONFACTORY_H

operationfactory.cpp

#include "operationfactory.h"

OperationFactory::OperationFactory()
{
}

operation* OperationFactory::createOperation(string operStr)
{
operation *oper = NULL;

if( operStr == "+" )
oper = new OperationAdd();
else if( operStr == "-" )
oper = new OperationSub();
else if( operStr == "*" )
oper = new OperationMul();
else if( operStr == "/" )
oper = new OperationDiv();

return oper;
}


main.cpp

#include <iostream>
#include <string>
#include "operationfactory.h"

using namespace std;

int main()
{
cout << "Simple Factory test" << endl;

operation *oper = NULL;
OperationFactory factory;
oper = factory.createOperation("/");
oper->strA = 1.1;
oper->strB = 2.2;
double result = oper->getResult();
cout  << "result: " << result << endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: