The Adapter design pattern is a structural pattern that allows the interface of an existing class to be used as another interface. It acts as a bridge between two incompatible interfaces, making them work together. This pattern involves a single class, known as the adapter, which is responsible for joining functionalities of independent or incompatible interfaces.
The objective is to make the Adaptee of the Target interface using an Adapter.
Defines the interface expected by the client. It represents the set of operations that the client code can use.
The existing class or system with an incompatible interface that needs to be integrated into the new system.
A class that implements the target interface and internally uses an instance of the adaptee to make it compatible with the target interface.
The code that uses the target interface to interact with objects. It remains unaware of the specific implementation details of the adaptee and the adapter.
public interface Printer {
void print(String message);
}
public class LegacyPrinter {
public void printDocument(String message) {
System.out.println(message);
}
}
public class PrinterAdapter implements Printer{
private LegacyPrinter legacyPrinter;
public PrinterAdapter(LegacyPrinter legacyPrinter) {
this.legacyPrinter = legacyPrinter;
}
@Override
public void print(String message) {
legacyPrinter.printDocument(message);
}
}
public class Client {
public static void main(String[] args) {
Printer printer = new PrinterAdapter(new LegacyPrinter());
printer.print("Hello, World!");
}
}