InfoQ|你应该了解的5种TypeScript设计模式( 二 )
但如果你决定使用工厂方法模式 , 则可以执行以下操作:
本文插图
现在 , 创建新对象所需的代码被封装到一个新类中 , 每种交通工具类型都对应一个 。 这样如果将来需要添加新类型 , 则只需添加一个新的类 , 不必修改任何现有的类 。
来看看我们如何使用 TypeScript 来实现这一点: interface Vehicle { move: void } //The classes we care about, the "move" method is where our "business logic" would live class Car implements Vehicle { public move: void { console.log("Moving the car!") } } class Bicycle implements Vehicle { console.log("Moving the bicycle!") } } class Plane implements Vehicle { console.log("Flying the plane!") } } //The VehicleHandler is "abstract" because noone is going to instantiate it //We want to extend it and implement the abstract method abstract class VehicleHandler { //This is the method real handlers need to implement public abstract createVehicle: Vehicle //This is the method we care about, the rest of the business logic resides here public moveVehicle: void { const myVehicle = this.createVehicle myVehicle.move } } //Here is where we implement the custom object creation class PlaneHandler extends VehicleHandler{ public createVehicle: Vehicle { return new Plane } } class CarHandler extends VehicleHandler{ return new Car } } class BicycleHandler extends VehicleHandler{ return new Bicycle } } /// User code... const planes = new PlaneHandler const cars = new CarHandler planes.moveVehicle cars.moveVehicle本质上 , 我们最终关心的是自定义处理程序(handler) 。 之所以叫它们处理程序 , 是因为它们不仅负责创建对象 , 而且具有使用它们的逻辑(如 moveVehicle 方法所示) 。 这种模式的优点在于 , 如果要添加新的类型 , 你要做的就是添加其交通工具类和其处理程序类 , 而无需改动其他类的代码 。
观察者 在所有模式中 , 我最喜欢的是观察者 , 这是因为我们可以用它来实现的行为类型 。 听说过 ReactJS 吗?它就是基于观察者模式的 。 前端 JavaScript 中的事件处理程序听过吗?也是基于它的 , 起码理论上是一致的 。
关键在于 , 通过观察者模式 , 你可以实现它们以及更多事物 。
本质上 , 这种模式表明你具有一组观察者对象 , 这些对象将对观察到的实体的状态变化做出反应 。 为了做到这一点 , 一旦观察端收到更改 , 就会调用一个方法来通知观察者 。
实践中这种模式相对容易实现 , 来看代码:
type InternalState = { event: String } abstract class Observer { abstract update(state:InternalState): void
推荐阅读
- 中年|全球饮茶风尚兴起 你真的了解袋泡茶吗?
- 京东|常说 AMD YES,却不知选哪款 A 卡好?或许应该看看这些
- 品谷农产品|专业的软件开发流程,应该是怎样的呢?
- 手机|当手机失窃信息被盗后我们应该怎么办?
- 科学,NASA|月球之旅应该带什么?NASA邀请人们分享心中答案
- 这样做|和平精英:萌新最易犯守楼误区,千万别卡楼梯口,你应该这样做
- 手机|手机选购先看需求,主力机或者备用机?这些价位也需要了解
- 达蒙砂轮|价格再次跌至谷底!切割片生产厂家究竟该如何定价?一、了解产品对于客户的价值二、细分目标市场生产差异化产品三、顺应市场变化,不断创
- 管径|管道天天见,管径搞不懂?一文了解De、DN、D、d、Φ区别
- 电视|还在为孩子看电视伤视力而烦恼?海信激光电视了解下
