Adapter
suggest changeAdapters are used to convert the interface of a given class, known as an Adaptee, into another interface, called the Target. Operations on the Target are called by a Client, and those operations are adapted by the Adapter and passed on to the Adaptee.
In Swift, adapters can often be formed with protocols. In the following example, a client that can communicate with the Target gains the ability to call Adaptee behavior through an adapter.
// 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()
}
}
Example flow of a one-way adapter: Client -> Target -> Adapter -> Adaptee
Adapters can also be bi-directional, and these are known as two-way adapters. A two-way adapter may be useful when two different clients need to view an object differently.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents