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

设计模式C++实现五:工厂方法模式

2015-05-11 12:09 387 查看
工厂方法模式(Factory Method):定义一个用于封建对象的接口,让子类觉得史丽华哪一个类,工厂方法使一个类的实例化延迟到其子类。

简单工厂模式优点 :工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖。但是因为我们需要根据客户端的输入来修实例化类,如果我们要增加类的话,我们需要修改工厂类方法,把该类加入其中,这意味着我们不但对扩展开发了,对修改也开发了,违背了开放-封闭原则。这就可以用工厂方法来解决这个问题。

工厂方法模式实现时,客户端需要决定实例化哪一个工厂来实现运算类,选择判断的问题还是存在的,也就是说,工厂方法把简单工厂的内部逻辑判断移到了客户端代码来进行,你想要增加功能,本来是改工厂类的,而现在是修改客户端。

<pre name="code" class="cpp">#ifndef FACTORY_MEANS_H
#define FACTORY_MEANS_H
#include<iostream>
using namespace std;

class Operation
{

protected:
double opA, opB;
public:
bool SetValue(double& n, double& m);
virtual double GetResult()const = 0;
};

class OperationAdd :public Operation
{
double GetResult()const;
};

class  OperationSub :public Operation
{
double GetResult()const;
};

class OperationMul :public Operation
{
double GetResult()const;
};

class OperationDiv :public Operation
{
double GetResult()const;
};

class IFactory
{
public:
virtual Operation *CreatOperation()=0;
};

class AddFactory : public IFactory
{
public:
Operation *CreatOperation()
{
return new OperationAdd();
}
};

class SubFactory : public IFactory
{
public:
Operation *CreatOperation()
{
return new OperationSub();
}
};

class MulFactory : public IFactory
{
public:
Operation *CreatOperation()
{
return new OperationMul();
}
};

class DivFactory : public IFactory
{
public:
Operation *CreatOperation()
{
return new OperationDiv();
}
};
bool Operation::SetValue(double &n, double &m)
{
opA = n;
opB = m;
return true;
}

double OperationAdd::GetResult()const
{
double result;
result = opA + opB;
return result;
}

double OperationSub::GetResult()const
{
double result;
result = opA - opB;
return result;
}

double OperationMul::GetResult()const
{
double result;
result = opA * opB;
return result;
}

double OperationDiv::GetResult()const
{
if (opB == 0){ cout << "opB in OperationDiv can't be zero.\n"; return 0.00000001; }
double result;
result = opA / opB;
return result;
}

#endif




#include"FactoryMeans.h"

int main()
{
IFactory *operA = new AddFactory;
Operation *opera = operA->CreatOperation();
IFactory *operS = new SubFactory;
Operation *opers = operS->CreatOperation();
IFactory *operM = new MulFactory;
Operation *operm = operM->CreatOperation();
IFactory *operD = new DivFactory;
Operation *operd = operD->CreatOperation();
double a, b;
while (cin >> a&&cin >> b)
{
opera->SetValue(a,b );
cout << "the result of " << a << " add " << b << " equal " << opera->GetResult() << endl;
opers->SetValue(a, b);
cout << "the result of " << a << " sub " << b << " equal " << opers->GetResult() << endl;
operm->SetValue(a, b);
cout << "the result of " << a << " mul " << b << " equal " << operm->GetResult() << endl;
operd->SetValue(a, b);
cout << "the result of " << a << " div " << b << " equal " << operd->GetResult() << endl;
}

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