Adapter Design Pattern

Emrah Turan
2 min readNov 5, 2023

--

The Adapter Design Pattern is a design pattern used to make two different interfaces work together seamlessly.

Let’s consider that in our application, there is an identity scanning module. Suppose our existing module has become dysfunctional due to changes in the identity system, and we need to integrate the new identity scanning module developed by ABC Company into the project.

In our current system, the identity scanning process is performed using the “scan()” function of the “CustomScanner” class, which implements the “IdScannerProtocol” protocol.

protocol IdScannerProtocol {
func scan()
}

final class CustomScanner: IdScannerProtocol {
func scan() {
print("id scanned")
}
}

In our application designed according to SOLID principles, the “scanner” variable is defined as an “IdScannerProtocol” and is created from a class that implements this protocol.

let scanner: IdScannerProtocol = CustomScanner()
scanner.scan()

The identity scanning module obtained from ABC Company performs the scanning process using the “scanner()” function.

class ABCScanner {
func scanner() {
print("id scanned")
}
}

Since our application performs identity scanning according to the “IdScannerProtocol” protocol, we need to make this new module we received from the outside compatible with the “IdScannerProtocol.” This is where the Adapter Design Pattern comes into play.

class ABCScannerAdapter: IdScannerProtocol {
private let abcScanner: ABCScanner

init(abcScanner: ABCScanner) {
self.abcScanner = abcScanner
}

func scan() {
abcScanner.scanner()
}
}

Our adapter is ready, and all we need to do is use the “ABCScannerAdapter” class instead of “CustomScanner.” This way, we can seamlessly integrate ABC Company’s identity scanning module into our existing system.

//let scanner: IdScannerProtocol = CustomScanner()
let scanner: IdScannerProtocol = ABCScannerAdapter(abcScanner: ABCScanner())
scanner.scan()

--

--