Adapter Pattern

將一個 class 的 interface 轉換成另一個 interface 供其他人使用,讓原本不相容的 interface 可以相容。

一個轉接頭的概念。

使用情境

不想改其他使用 class A 的 code 卻想用 class B 達成相同功能時,以 Adapter 將 class B 的 interface 轉成 class A。

Adapter 因為受限 Adaptee 的能力,不一定能完美 implement interface 所提供的功能,這種時候通常用文件(就大家講好)或 exception 等等方式處理。之前一直以為 Adpater 要完全 implement interface 提供的功能,遇到受限的狀況就有點 confuse 這樣是不是 adpater…

UML

Adapter Pattern (合成)

Client 只知道 Target 的 interface,不知道 Adaptee 的 interface,Class 跟 Adaptee 之間是鬆綁的。如果需要同時使用兩種 interface,Adapater 也可以 implement 多個 Target interface,例如有 Target1 及 Target2 兩個 interface,有些地方原本使用 Target1,後來新寫的 code 使用 Target2,Adapter 同時支援兩者就可以不改動到原有的 code。

我比較習慣用合成讓 Adapter 使用 Adaptee,有另一種做法是用繼承,沒很懂這樣用的好處跟時機,先記著有這種方式:

Adapter Pattern (繼承)

跟其他 pattern 比較

  • Adapter 是做 interface 轉換。
  • Facade 是為了提供簡單的 interface 讓其他人易於操作 sub system,Adapter 跟 Facade 的差別在「目的」。
  • Decorator 是加功能。