Adapter Design Pattern
The Adapter pattern enables objects with incompatible interfaces to work together. It acts as a bridge, transforming one interface into another so that otherwise incompatible components can collaborate seamlessly.
Complexity: ⭐️★★
Popularity: ⭐️⭐️⭐️
The Problem Adaptor Solves
Imagine, you’ve built a music streaming app that processes playlists in MP3 format. Your app works flawlessly until you want to integrate a sophisticated audio processing library that only works with FLAC format.
If the library were open source, you could modify it to work with FLAC. However, doing so might break existing code that relies on the library’s original design, and creating additional problems. Also it is violates the Single Responsibility Principle.
Here's the another common analogy: Imagine you’re traveling internationally with your laptop charger. You have a perfectly good charger, but the wall socket has a completely different shape. What do you need? A power adapter! This everyday scenario perfectly illustrates the Adapter Design Pattern in software development.
The Adaptor Solution
To solve this, you can create an adapter — a special object that converts the interface of one object so another object can understand it. This adapter wraps one object and hides the complexity of conversion from the rest of the application. The wrapped object remains unaware of the adapter’s presence.
Get Ahmet Tarik DÖNER’s stories in your inbox
Join Medium for free to get updates from this writer.
Here’s how it works in practice:
- The adapter uses an interface compatible with one of the existing objects.
- Through this interface, the existing object can safely call the adapter’s methods.
- When the adapter receives a call, it translates the request and passes it to the second object in a format that the object expects.
In our music streaming app, we could create an MP3-to-FLAC adapter. The application would then communicate with the analytics library through this adapter. When the adapter receives data in MP3 format, it converts it to FLAC and then passes it to the analytics library.
The Adaptor Structure
This structure depends on the object composition principle, and the object called object adapter. Also we have class adapters that uses inheritance. The adapter inherits both interface at the same time. But it supports only when the programming language supports multiple inheritance such as C++.
Domain of Applicability
- You need to use an existing class whose interface doesn’t match your needs
- You want to create a reusable class that cooperates with classes having incompatible interfaces
- You need to integrate third-party libraries without modifying their code
- You have multiple components with similar functionality but different interfaces
How does the Adapter Implements:
- Identify at least two classes with incompatible interfaces.
- Define the client interface to specify how clients should interact with the service.
- Create an adapter class that follows the client interface.
- Add a field to the adapter class to store a reference to the service object. Typically, this reference is initialized via the constructor, but in some cases, it’s convenient to pass it directly when calling the adapter’s methods.
- Implement all methods of the client interface in the adapter class. Each method should delegate most of the real work to the service object, handling only interface or data formatting as needed.
- Ensure the client interacts with the adapter through the client interface, allowing you to modify or extend adapters without affecting existing client code.
Conceptual Example
/// Target defines the domain-specific interface used by the client code.
class Target {
func request() -> String {
"Target: The default target's behavior."
}
}
/// Adaptee contains some useful behavior, but its interface is incompatible with the existing client code.
/// Te Adaptee needs some adaptation before the client code can use it.
class Adaptee {
func specificRequest() -> String {
".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 {
"ADAPTER: (TRANSLATED) " + adaptee.specificRequest().reversed()
}
}
class Client {
static func someClientCode(target: Target) {
print(target.request())
}
}
class TestAdapterConceptual {
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 dont understand it.")
print("Adaptee: " + adaptee.specificRequest())
print("Client: But i can work with it via the Adapter:")
Client.someClientCode(target: Adapter(adaptee))
}
}
let test = TestAdapterConceptual()
test.testAdapterConceptual()Real World Example
import UIKit
protocol AuthService {
func presentAuthFlow(from viewController: UIViewController)
}
class FacebookAuthSDK {
func presentAuthFlow(from viewController: UIViewController) {
print("Facebook WebView has been shown.")
}
}
extension FacebookAuthSDK: AuthService {
/// This extension tells compiler that both SDKs have the same interface.
}
class XAuthSDK {
func startAuthorization(with viewController: UIViewController) {
print("X WebView has been shown. Users will be happy.")
}
}
extension XAuthSDK: AuthService {
/// This is an Adapter
///
/// Yeah, we are able to not create another class and just an existing one.
func presentAuthFlow(from viewController: UIViewController) {
print("The Adapter is called! Redirecting to the original method...")
self.startAuthorization(with: viewController)
}
}
class TestAdapterRealWorld {
func testAdapterRealWorld() {
print("Starting an authorization via Facebook")
startAuthorization(with: FacebookAuthSDK())
print("Starting an authorization via X")
startAuthorization(with: XAuthSDK())
}
func startAuthorization(with service: AuthService) {
let topViewController = UIViewController()
service.presentAuthFlow(from: topViewController)
}
}
let test = TestAdapterRealWorld()
test.testAdapterRealWorld()Stackademic 🎓
Thank you for reading until the end. Before you go:
- Please consider clapping and following the writer! 👏
- Follow us X | LinkedIn | YouTube | Discord | Newsletter | Podcast
- Create a free AI-powered blog on Differ.
- More content at Stackademic.com











