設(shè)計模式在 TypeScript 中的應(yīng)用 - 策略模式

定義

定義一系列的算法,把它們一個個封裝起來,并且使它們可以相互替換。

實現(xiàn)

思路:創(chuàng)建表示各種策略的對象,和一個行為隨著策略對象改變而改變的 context 對象。

一個簡單的加減乘例子:

interface Compute<T> {
  computeF (num1: T, num2: T): T
}

// 創(chuàng)建策略對象
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}`
  }
}

// 創(chuàng)建行為類
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

復(fù)雜一點的例子(打怪):

// 武器接口
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

 // 設(shè)置武器
  public setWeapon (weapon: Weapon): void {
    this.weapon = weapon
  }
  
  // 設(shè)置技能
  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()

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容