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:
Target
is the interface that the client code expects. In this case, it has arequest
method.Adaptee
is the class with the specific functionality that we want to adapt. It has aspecificRequest
method.Adapter
is the class that implements theTarget
interface and contains an instance ofAdaptee
. It delegates therequest
method to thespecificRequest
method ofAdaptee
.- In the client code, we create an instance of
Adaptee
, then create an instance ofAdapter
and pass theAdaptee
instance to it. Finally, we call therequest
method of theTarget
interface (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.