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
推荐阅读
- 点球|马宁100%误判!天津泰达点球被扑,按照新规则,应该重罚
- 吃货|快餐酸菜鱼加盟流程:了解完品牌后,最后还要经过培训
- 游戏资讯小驿站|我的世界拔刀剑模组:独特设定!帮助玩家更深入了解刀的制作
- 没蜡笔的小新|“整容脸”应该被鄙视吗?医生告诉你千篇一律的好看皮囊如何而来
- TopGame|FIFA足球世界 氪金游戏平民如何生存?最详白嫖套路了解下
- 刺刀|CSGO皮肤指南:刺刀应该怎么挑选?这款比穷人之水还便宜
- 王者荣耀|碎片商店免费换皮肤真香?大仙意外曝光5条规律,了解后赚大了!
- 【】詹眉又比肩OK组合纪录 沃帅:戴维斯才应该是DPOY
- 「浪姐」浪姐成团:30+的女性应该活成什么样子?她们给出了最好的答案
- 时尚广州|T恤的标语你了解过吗?揭秘衣服上那些奇怪的字句
