Structural Design Pattern: Adapter
Adapter is a structural design pattern that allows objects with incompatible interfaces to collaborate.
Table of Contents
1. Adapter Design Pattern
Adapter is usually applied when endpoint processors cannot agree on the format of data, e.g., producers generates .xml files while consumers processes .json files.
So we can create adapters, which converts the interface of one object so that other objects can understand it. The adapter also wraps the object to hide the complexity of conversion. For example, if our program uses class A, we want to use another class B who have incompatible interfaces. We can create a new class BtoA_Adapter that exposes A-style APIs but its private fields are B, and use this adapter class as if the object is of class A.
Adapters can also be used to help objects with different interfaces collaborate:
- The adapter gets an interface
- An existing object can call the adapter’s methods using this interface
- Upon receiving a call, the adapter passes the request to the second object, but in a format and order that the second object expects.
1.1. How to Implement?
1.1.1. Object Adapter
We should have a ClientInterface that describes a protocol for other classes to follow, to be able to collaborate with the client code, say, the protocol is invoke(data) where data must follow a certain format. Also suppose some Service class with method serve(data_json) that requires special format.
The Adapter class implements the ClientInterface interface. The client have a pointer of class ClientInterface but points to an Adapter instance. Upon calling Adapter.invoke(data), Adapter converts data into data_json and invokes Service.serve(data_json).
The key is to understand the chain of invocation: the client calls the adapter through interface; then, the adapter calls the service through the service’s methods.
1.1.2. Class Adapter
Similar to Object Adapter, the only difference is that Adapter class is now a subclass of Service besides implementing ClientInterface interface.
The chain of invocation is: the client calls the adapter through interface; then, the adapter calls the inherited service methods.