# 第 16 章 策略模式

這邊文章告訴你如何在弱類型語言上,優雅地聲明變量。javascript

@(js設計模式)java

概念

  • 不一樣策略分開處理
  • 避免出現大量 if...else 或者 switch...case
  • js 中未找到經典應用場景

示例

錯誤寫法一

class User {
  constructor (user) {
    this.user = user
  }
  buy () {
    const user = this.user
    // 錯誤寫法一
    if (user === 'vip') {
      console.log('會員購買')
    }
    if (user === 'normal') {
      console.log('普通的用戶')
    }
    if (user === 'superVip') {
      console.log('超級會員')
    } 
  }
}

const vip = new User('vip')
vip.buy()
const normal = new User('normal')
normal.buy()
const superVip = new User('superVip')
superVip.buy()

錯誤寫法二

class User {
  constructor (user) {
    this.user = user
  }
  buy () {
     const user = this.user
        switch (user) {
      case 'vip':
        console.log('會員購買')
        break;
      case 'normal':
        console.log('普通的用戶')
        break;
      case 'superVip':
        console.log('超級會員')
        break;
      default:
        console.log('普通的用戶')
        break;
    }
  }
}

const vip = new User('vip')
vip.buy()
const normal = new User('normal')
normal.buy()
const superVip = new User('superVip')
superVip.buy()

正確寫法

按照多少個不一樣的用戶來分開多少個不一樣策略設計模式

class Vip {
  buy() {
    console.log('會員購買')
  }
}
class Normal {
  buy() {
    console.log('普通的用戶')
  }
}
class SuperVip {
  buy() {
    console.log('超級會員')
  }
}
const vip = new Vip()
vip.buy()
const normal = new Normal()
normal.buy()
const superVip = new SuperVip()
superVip.buy()

優化(推薦)優化

爲何優化?一般狀況下儘可能少聲明類(簡化也不要 開示例代碼多少,要看實現代碼應用多少)this

按照用戶類型,用戶購買內容分紅兩個策略設計

const UserType = {
  Vip: 'vip',
  Normal: 'normal',
  SuperVip: 'superVip'
}
const UserTypeName = {
  [UserType.Vip]: '會員購買',
  [UserType.SuperVip]: '超級會員',
  [UserType.Normal]: '普通的用戶'
}

class User {
  constructor (user) {
    this.user = user
  }

  buy () {
    console.log(UserTypeName[this.user])
  }
}

const vip = new User(UserType.Vip)
vip.buy()
const normal = new User(UserType.Normal)
normal.buy()
const superVip = new User(UserType.SuperVip)
superVip.buy()
相關文章
相關標籤/搜索