Skip to main content

Swift Example

/// Adapter Design Pattern
///
/// Intent: Provides a unified interface that allows objects with incompatible
/// interfaces to collaborate.

import XCTest

/// The Target defines the domain-specific interface used by the client code.
class Target {

func request() -> String {
return "Target: The default target's behavior."
}
}

/// The Adaptee contains some useful behavior, but its interface is incompatible
/// with the existing client code. The Adaptee needs some adaptation before the
/// client code can use it.
class Adaptee {

public func specificRequest() -> String {
return ".eetpadA eht fo roivaheb laicepS"
}
}

/// The Adapter makes the Adaptee's interface compatible with the Target's
/// interface.
class Adapter: Target {

private var adaptee: Adaptee

init(_ adaptee: Adaptee) {
self.adaptee = adaptee
}

override func request() -> String {
return "Adapter: (TRANSLATED) " + adaptee.specificRequest().reversed()
}
}

/// The client code supports all classes that follow the Target interface.
class Client {
// ...
static func someClientCode(target: Target) {
print(target.request())
}
// ...
}

/// Let's see how it all works together.
class AdapterConceptual: XCTestCase {

func testAdapterConceptual() {
print("Client: I can work just fine with the Target objects:")
Client.someClientCode(target: Target())

let adaptee = Adaptee()
print("Client: The Adaptee class has a weird interface. See, I don't understand it:")
print("Adaptee: " + adaptee.specificRequest())

print("Client: But I can work with it via the Adapter:")
Client.someClientCode(target: Adapter(adaptee))
}
}
Client: I can work just fine with the Target objects:
Target: The default target's behavior.
Client: The Adaptee class has a weird interface. See, I don't understand it:
Adaptee: .eetpadA eht fo roivaheb laicepS
Client: But I can work with it via the Adapter:
Adapter: (TRANSLATED) Special behavior of the Adaptee.