Adapter Pattern
Description:
The Adapter Pattern is a structural design pattern that allows objects with incompatible interfaces to work together. It acts as a bridge between two incompatible interfaces, enabling them to collaborate without altering their source code. The Adapter Pattern is useful when you want to reuse existing classes or integrate third-party libraries that don’t quite fit your desired interface.
How it’s Used:
- Identify Interfaces: Identify the two interfaces that need to work together but are incompatible.
- Adapter Class: Create an adapter class that implements the interface expected by the client code (the target interface) while containing an instance of the class with the incompatible interface (the adaptee).
- Adapter Methods: Within the adapter class, implement methods that map the methods of the target interface to the corresponding methods of the adaptee interface.
- Client Code: In the client code, use the adapter class to interact with the adaptee class as if it implements the target interface.
Example:
Suppose you have a legacy class OldSystem with an interface that is incompatible with your modern system, but you need to integrate the legacy functionality. Here’s how the Adapter Pattern can be applied:
- Incompatible Legacy Class (Adaptee): Define the
OldSystemclass with its existing interface.
public class OldSystem {
public void doOldStuff() {
System.out.println("Doing old stuff in the legacy system.");
}
}- Target Interface: Define the
NewSysteminterface that your modern system expects.
public interface NewSystem {
void doNewStuff();
}- Adapter Class: Create an adapter class
Adapterthat implements theNewSysteminterface and contains an instance of theOldSystemclass.
public class Adapter implements NewSystem {
private OldSystem oldSystem;
public Adapter(OldSystem oldSystem) {
this.oldSystem = oldSystem;
}
@Override
public void doNewStuff() {
// Delegate the new system's request to the old system's method
oldSystem.doOldStuff();
}
}- Client Code: In your modern system, use the
Adapterclass to work with theOldSystemas if it were aNewSystem.
public class Client {
public static void main(String[] args) {
OldSystem legacySystem = new OldSystem();
NewSystem adapter = new Adapter(legacySystem);
// Use the adapter to perform new system operations
adapter.doNewStuff();
}
}By using the Adapter Pattern, you can integrate the legacy OldSystem class seamlessly into your modern system without changing the code of the legacy class. The adapter serves as a bridge, translating calls from the new system’s interface to the old system’s interface, allowing them to work together.