【设计模式(一)】简单工厂——计算器用例

mac2022-06-30  26

温故而知新,工作半年来最大的感触就是知识储备的不足与基础知识的薄弱,特此复习一下23种设计模式,并用一些典型的应用场景来模拟该种模式的使用。

暂时使用的语言是微软的Typescript,与C#、JAVA等语言在某些地方会有一些出入。

简单工厂(Simple Factory)

首先它不属于23种设计模式,但之后的抽象工厂、工厂方法模式都由此演化而来,而且在工厂创建类比较少的情况下也会使用,因此算是设计模式中的”父类“了。

废话不多说,先上需求:做一个简单的计算器(加减乘除)。

类图

 

Operation 运算类

class Operation { private _numberA: number; private _numberB: number; constructor(){ } get numberA(): number { return this._numberA; } set numberA(num: number) { this._numberA = num; } get numberB(): number { return this._numberB; } set numberB(num: number) { this._numberB = num; } /** * 得到结果 */ public GetResult(): number { let result: number = 0; return result; } } OperationAdd、OperationSub、OperationMul、OperationDiv 加减乘除类(继承运算类) /**加类**/ class OperationAdd extends Operation { constructor() { super(); } public GetResult(): number { super.GetResult(); let result: number = 0; result = this.numberA + this.numberB; return result; } } /**减类**/ class OperationSub extends Operation { constructor() { super(); } public GetResult(): number { super.GetResult(); let result: number = 0; result = this.numberA - this.numberB; return result; } } /**乘类**/ class OperationMul extends Operation { constructor() { super(); } public GetResult(): number { super.GetResult(); let result: number = 0; result = this.numberA * this.numberB; return result; } } /**除类**/ class OperationDiv extends Operation { constructor() { super(); } public GetResult(): number { super.GetResult(); let result: number = 0; if (this.numberB == 0) throw (new Error("除数不能为0!")); result = this.numberA / this.numberB; return result; } } OperationFactory 简单运算工厂类(将以上类通过不同条件实例化) class OperationFactory { constructor() { } public static createOperate (operate: string): Operation { let oper: Operation = null; switch(operate) { case "+": oper = new OperationAdd(); break; case "-": oper = new OperationSub(); break; case "*": oper = new OperationMul(); break; case "/": oper = new OperationDiv(); break; } return oper; } }

Main 客户端测试

let oper: Operation; oper = OperationFactory.createOperate("/"); //输入条件,生产除类的实例 oper.numberA = 5; //输入数字A oper.numberB = 0; //输入数字B let res: number = oper.GetResult(); //得出运算结果 console.log(oper.numberA,oper.numberB,res); //报错:除数不能为0!

 

优缺点

优点:只需要传入一个正确的参数,就可以获取所需要的对象而无须知道其创建细节。

缺点:工厂类的职责相对过重,增加新的产品需要修改工厂类的判断逻辑,违背开闭原则。

 

转载于:https://www.cnblogs.com/harrickheng/p/11223052.html

相关资源:计算工厂161.exe
最新回复(0)