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

优点与缺点

这个模式的内容其实很容易理解,实作方式也相当的简单。而外观模式常见的地方不仅仅只在於包装复杂的函式,很多时候也会包装整个应用程序当中的子系统,让程序码的操作本身更为简洁。对使用者来说,可以不用去知道背後系统的实作细节。

但缺点就是,我们将许多的操作都放在同一个地方,因此实作外观模式的这个物件将会越来越大。


<<:  [NestJS 带你飞!] DAY27 - Swagger (下)

>>:  Day 28 - 将 Specification 後台储存资料提取後,送至前台渲染 Specification 版面内容区块 - MSSQL 查询精灵 - ASP.NET Web Forms C#

django新手村2 ------创建models

上一篇提到 主urls->次urls->views->models->vie...

想要弹性类别吗,让类别当参数吧:泛型 Generics

宽广的室外网球场上,学生们正在做发球考试的练习。 「嘿!」女孩左手将球向上轻抛,右手握拍奋力用全身的...

Buy Store Location Data: Best Store Database Provider 2021

Store location data is information about the geogr...

Unity 资料库开发2(webservice)

接连上一篇试了一些unity 连线的方式 最後方案底定,使用 webservice 的技术 ,然後连...

【Day 12】C 语言的 if 条件判断(上)

写程序的时候,我们常常需要「判断」某些条件,当条件成立、条件为"真"的时候,执行某一段程序码,而条件...