定义一系列的算法,把它们一个个封装起来,而且使它们能够相互替换。算法
思路:建立表示各类策略的对象,和一个行为随着策略对象改变而改变的 context 对象。typescript
一个简单的加减乘例子:this
interface Compute<T> { computeF (num1: T, num2: T): T } // 建立策略对象 class ComputeAdd implements Compute<number> { public computeF ( num1: number, num2: number ): number { return num1 + num2 } } class ComputeSub implements Compute<number> { public computeF ( num1: number, num2: number ): number { return num1 - num2 } } class ComputeMul implements Compute<String> { public computeF ( num1: String, num2: String ): String { return `${num1} + ${num2}` } } // 建立行为类 class Context { public compute: Compute<any> public constructor (compute: Compute<any>) { this.compute = compute } public excuteCompute ( num1: number, num2: number ): number { return this.compute.computeF(num1, num2) } } let context1 = new Context(new ComputeAdd()) .excuteCompute(1, 2) let context2 = new Context(new ComputeSub()) .excuteCompute(1, 2) let content3 = new Context(new ComputeMul()) .excuteCompute(1, 2) console.log(context1, context2, content3) // 3, -1, 1 + 2
复杂一点的例子(打怪):code
// 武器接口 interface Weapon { useWeapon (): void } // 技能接口 interface Skill { useSkill (): void } // 武器类 class Gun implements Weapon { public useWeapon () { console.log( 'Weapon: Gun') } } class Stick implements Weapon { public useWeapon () { console.log('Weapon: Stick') } } // 技能类 class Magic implements Skill { public useSkill () { console.log('Skill: Magic') } } class Kongfu implements Skill { public useSkill () { console.log('Skill: Chinese Kongfu') } } // 抽象类,用于给其余类继承 abstract class Way { // 武器 public weapon: Weapon // 技能 public skill: Skill // 设置武器 public setWeapon (weapon: Weapon): void { this.weapon = weapon } // 设置技能 public setSkill (skill: Skill): void { this.skill = skill } public getWeaponAndSkill (): void { this.weapon.useWeapon() this.skill.useSkill() } // 抽象方法 public abstract saySome (): void } class SimpleWay extends Way { public constructor () { super() this.weapon = new Gun() this.skill = new Magic() } public saySome () { console.log('屠龙宝刀,点击就送') } } const way = new SimpleWay() way.saySome() console.log('=======') way.getWeaponAndSkill() console.log('=======') way.setWeapon(new Stick) way.setSkill(new Kongfu) way.getWeaponAndSkill()