介面卡

介面卡用於將給定類的介面(稱為 Adaptee )轉換為另一個稱為 Target 的介面。對目標的操作由一個叫做客戶端,並且這些操作都適合通過介面卡和傳遞到適配者。

在 Swift 中,通常可以通過使用協議來形成介面卡。在以下示例中,能夠與 Target 通訊的客戶端能夠通過使用介面卡來執行 Adaptee 類的功能。

// The functionality to which a Client has no direct access
class Adaptee {
    func foo() {
        // ...
    }
}

// Target's functionality, to which a Client does have direct access
protocol TargetFunctionality {
    func fooBar() {}
}

// Adapter used to pass the request on the Target to a request on the Adaptee
extension Adaptee: TargetFunctionality {
    func fooBar() {
        foo()
    }
}

單向介面卡的示例流程:Client -> Target -> Adapter -> Adaptee

介面卡也可以是雙向的,這些被稱為雙向介面卡。當兩個不同的客戶端需要以不同方式檢視物件時,雙向介面卡可能很有用。