Design Patterns#6 Adapter Pattern
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, making them compatible without changing their source code. This pattern is especially useful when integrating new functionality or libraries into an existing system.
Here’s a simple example of the Adapter Pattern in Java:
Suppose you have an existing class OldSystem
with a method legacyOperation()
:
class OldSystem {
void legacyOperation() {
System.out.println("Legacy operation is performed.");
}
}
You want to use this OldSystem
in a new system that expects an interface called NewSystemInterface
with a method newOperation()
:
interface NewSystemInterface {
void newOperation();
}
To make OldSystem
compatible with the new system, you can create an adapter class that implements the NewSystemInterface
and delegates calls to OldSystem
's legacyOperation()
method:
class OldSystemAdapter implements NewSystemInterface {
private OldSystem oldSystem;
OldSystemAdapter(OldSystem oldSystem) {
this.oldSystem = oldSystem;
}
@Override
public void newOperation() {
oldSystem.legacyOperation();
}
}
Now, you can use the OldSystem
in your new system by creating an instance of the adapter:
public class Main {
public static void main(String[] args) {
OldSystem oldSystem = new OldSystem();
NewSystemInterface adapter = new OldSystemAdapter(oldSystem);
// The new system can use the old system through the adapter.
adapter.newOperation();
}
}
In this example, the OldSystemAdapter
acts as a bridge between the old system's interface (OldSystem
) and the new system's interface (NewSystemInterface
). This allows the new system to call newOperation()
on the adapter, which, in turn, delegates the call to the legacyOperation()
method of the OldSystem
class. This way, the incompatible interfaces are made compatible through the adapter, allowing them to work together seamlessly.