The Adapter Pattern is a structural design pattern that allows incompatible interfaces to work together. It acts as a bridge between two incompatible interfaces by converting the interface of a class into another interface that a client expects. This pattern involves a single class called Adapter, which is responsible for joining functionalities of independent or incompatible interfaces.
Let’s create a simple example using Java to illustrate the Adapter Pattern.
Step 1: Define Target Interface
Step 2: Create Adaptee Class
Step 3: Implement Adapter Class
Step 4: Client Code
Explanation:
Targetis the interface that the client code expects. In this case, it has arequestmethod.Adapteeis the class with the specific functionality that we want to adapt. It has aspecificRequestmethod.Adapteris the class that implements theTargetinterface and contains an instance ofAdaptee. It delegates therequestmethod to thespecificRequestmethod ofAdaptee.- In the client code, we create an instance of
Adaptee, then create an instance ofAdapterand pass theAdapteeinstance to it. Finally, we call therequestmethod of theTargetinterface (via theAdapter).
When you run the Client class, it will output:
Specific request from Adaptee
This demonstrates how the Adapter Pattern allows the client code to work with the Target interface while utilizing the functionality of the Adaptee class. The adapter acts as a bridge between the two interfaces.
