knowledge/technology/programming/patterns/structural/Adapter Pattern.md
2023-12-04 11:02:23 +01:00

64 lines
No EOL
2.9 KiB
Markdown

---
obj: concept
---
# 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:**
1. **Identify Interfaces**: Identify the two interfaces that need to work together but are incompatible.
2. **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).
3. **Adapter Methods**: Within the adapter class, implement methods that map the methods of the target interface to the corresponding methods of the adaptee interface.
4. **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 `OldSystem` class with its existing interface.
```java
public class OldSystem {
public void doOldStuff() {
System.out.println("Doing old stuff in the legacy system.");
}
}
```
- **Target Interface**: Define the `NewSystem` interface that your modern system expects.
```java
public interface NewSystem {
void doNewStuff();
}
```
- **Adapter Class**: Create an adapter class `Adapter` that implements the `NewSystem` interface and contains an instance of the `OldSystem` class.
```java
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 `Adapter` class to work with the `OldSystem` as if it were a `NewSystem`.
```java
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.