设计模式——工厂模式
2017-06-10 15:10
330 查看
问题描述: 使用工厂模式实现简单计算器的加减乘数功能。 github地址:https://github.com/lining91/FactoryPattern2 工厂方法模式,定义了一个用于创建对象的接口,封装对象的创建,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类中。 **与简单工厂的区别:** 简单工厂模式的优点是工厂类中包含了必要的逻辑判断,根据增加需求来动态的实例化相关的类,去除了与具体产品的依赖。 在简单工厂模式中,当增加需求时,需要修改原有的工厂类,增加新的类,对扩展开放了,对修改也开放了,违背了开放-封闭原则。 工厂模式中,当增加需求时,不需要修改原有的工厂类,只需要增加此类需求的类和相应的工厂类即可。符合开放-封闭原则。 **代码如下:** 操作类如下
// 操作基类 class Operation{ public: virtual int GetResult( int n1, int n2 ) = 0; }; // 加减乘数类 class OperationAdd : public Operation{ public: virtual int GetResult(int n1, int n2) { return n1 + n2; } }; class OperationSub : public Operation{ public: virtual int GetResult(int n1, int n2) { return n1 - n2; } }; class OperationMul : public Operation{ public: virtual int GetResult(int n1, int n2) { return n1 * n2; } }; class OperationDiv : public Operation{ public: virtual int GetResult(int n1, int n2) { if (n2 == 0) throw "除数不能为0!"; return n1 / n2; } };
工厂抽象类和工厂具体类:
// 抽象工厂类 class IFactory { public: virtual Operation* CreateOperation() = 0; }; // 具体工厂类 class AddFactory : public IFactory { public: Operation* CreateOperation() { return new OperationAdd(); } }; class SubFactory : public IFactory { public: Operation* CreateOperation() { return new OperationSub(); } }; class MulFactory : public IFactory { public: Operation* CreateOperation() { return new OperationMul(); } }; class DivFactory : public IFactory { public: Operation* CreateOperation() { return new OperationDiv(); } };
main 函数:
void main() { int n1 = 33; int n2 = 52; // 创建具体操作工厂类,如果需要修改新的计算方式,需要重新生成该类 IFactory* pFactory = new MulFactory(); if ( pFactory == NULL ) return; Operation* pOpe = pFactory->CreateOperation(); if (pOpe == NULL) return; try{ int nResult = pOpe->GetResult(n1, n2); cout << n1 << " * " << n2 << " is " << nResult << endl; } catch(char* pErr) { cout << pErr << endl; } delete pOpe; pOpe = NULL; delete pFactory; pFactory = NULL; system("pause"); }
运行结果如下:
当需要修改乘法运算为“+”运算时,只需要重新生成main函数中的IFactory* pFactory实例。降低代码的耦合度,对其余代码没有影响。
相关文章推荐
- 设计模式:工厂
- 简单工厂设计模式-设计模式(1)
- 设计模式之Factory工厂模式
- 设计模式之工厂方法
- 转:C#设计模式之简单工厂篇
- .NET中的设计模式一:工厂模式
- C#设计模式之简单工厂篇
- C#设计模式之简单工厂篇
- .NET实用设计模式:工厂模式(Factory)
- 抽象工厂设计模式(C#)
- .NET中的设计模式一:工厂模式 (转)
- 设计模式[2]-旧话重提之工厂模式
- 设计模式之(2)简单工厂模式
- 设计模式之 工厂方法(Factory)------对象创建型模式
- .NET中的设计模式一:工厂模式 选择自 lane_cn 的 Blog
- C#设计模式学习笔记---简单工厂模式
- Java设计模式:Factory(工厂模式)
- .NET中的设计模式一:工厂模式
- 设计模式[2]-旧话重提之工厂模式
- Java设计模式之工厂模式篇