iT邦幫忙

2021 iThome 鐵人賽

DAY 27
0
Software Development

幫自己搞懂物件導向和設計模式系列 第 27

Facade 外觀模式

在 Structural patterns 當中,最後要來談的是外觀模式。

外觀模式提供我們一個簡單方便的操作介面,其背後幫我們實現了複雜的操作。這樣的模式其實也很常見,譬如建立一個新的類別或函式,然後把原本複雜的邏輯給包裝起來,對使用者來說,他不用顧慮(也不用知道)複雜的實作內容,只要操作這個新的類別或函式就行了

簡單的例子如下。假設今天有三個類別,分別為 SugarMachine, MilkMachine, CoffeeMachine,當中都有不同的方法可以使用。

class SugarMachine {
  constructor(){}

  addBrownSugar(): string {
    return 'brown sugar'
  }

  addNormalSugar(): string {
    return 'sugar'
  }
}

class MilkMachine {
  constructor(){}

  addMilk(): string {
    return 'milk'
  }

  addOakMilk(): string {
    return 'oak milk'
  }
}

class CoffeeMachine {
  constructor(){}

  addDarkRoastCoffee(): string {
    return 'dark roast coffee'
  }

  addLightRoastCoffee(): string {
    return 'light roast coffee'
  }
}

如果我們今天想要讓客戶自己操作機器得到自己的飲品,那麼我們就需要教導使用者如何操作這三台機器,並且針對不同的需求做操作上的變化,那麼難度就會更加提升。

因此,不如我們就打造一台販賣機,只要使用者呼叫當中的一個方法,就能夠獲得想要的飲品。

這裡我們建立了 VendingMachine 類別,以及 latte, espresso, oakMilkLatte 三種方法,當中各自包含了對於 SugarMachine, MilkMachine, CoffeeMachine 的操作。

class VendingMachine {
  private coffeeMachine: CoffeeMachine
  private sugarMachine: SugarMachine
  private milkMachine: MilkMachine

  constructor(coffeeMachine: CoffeeMachine, sugarMachine: SugarMachine, milkMachine: MilkMachine) {
    this.coffeeMachine = coffeeMachine
    this.sugarMachine = sugarMachine
    this.milkMachine = milkMachine
  }

  latte(): string {
    return `latte - ${this.coffeeMachine.addLightRoastCoffee()} + ${this.milkMachine.addMilk()} + ${this.sugarMachine.addNormalSugar()}`
  }

  espresso(): string {
    return `espresso - ${this.coffeeMachine.addDarkRoastCoffee()}`
  }

  oakMilkLatte(): string {
    return `oak milk latte - ${this.coffeeMachine.addLightRoastCoffee()} + ${this.milkMachine.addOakMilk()} + ${this.sugarMachine.addNormalSugar()}`
  }
}

接著,我們就可以建立 vendingMachine 實例

const coffeeMachine = new CoffeeMachine()
const sugarMachine = new SugarMachine()
const milkMachine = new MilkMachine()

const vendingMachine = new VendingMachine(coffeeMachine, sugarMachine, milkMachine)

最後,呼叫不同的方法得到我們期待的飲品

vendingMachine.latte()
// latte - light roast coffee + milk + sugar

vendingMachine.espresso()
// espresso - dark roast coffee'

vendingMachine.oakMilkLatte()
// oak milk latte - light roast coffee + oak milk + sugar

優點與缺點

這個模式的內容其實很容易理解,實作方式也相當的簡單。而外觀模式常見的地方不僅僅只在於包裝複雜的函式,很多時候也會包裝整個應用程式當中的子系統,讓程式碼的操作本身更為簡潔。對使用者來說,可以不用去知道背後系統的實作細節。

但缺點就是,我們將許多的操作都放在同一個地方,因此實作外觀模式的這個物件將會越來越大。


上一篇
Proxy 代理模式
下一篇
Chain of Responsibility 責任鏈模式
系列文
幫自己搞懂物件導向和設計模式30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
juck30808
iT邦研究生 1 級 ‧ 2021-10-12 18:39:34

恭喜大大即將完賽XD !!!

我要留言

立即登入留言