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.
The Adapter Pattern converts the interface of a class into another interface that the client expects. It allows classes with incompatible interfaces to work together without changing their existing code.
Key features:
- Compatibility: Enables objects with incompatible interfaces to interact.
- Reusability: Reuses existing code without modification.
- Flexibility: Adapts interfaces dynamically at runtime.
- Legacy Code: Integrate legacy components with new systems.
- Third-Party Libraries: Adapt third-party libraries to fit your application's needs.
- Interface Mismatch: Resolve incompatibilities between interfaces.
The implementation of the Adapter Pattern can be found in:
RoundHole.java
: Represents the round hole (Client).RoundPeg.java
: Represents a round peg (Target).SquarePeg.java
: Represents a square peg (incompatible Adaptee).SquarePegAdapter.java
: Adapter to make a square peg fit into a round hole.Main.java
: Demonstrates the usage of the Adapter Pattern.
To see the Adapter Pattern in action, refer to the Main.java
file. It demonstrates how to use the adapter to fit a square peg into a round hole.
classDiagram
direction LR
class Client {
+request()
}
class Target {
+request()
}
class Adapter {
+request()
}
class Adaptee {
+specificRequest()
}
Client --> Target
Target <|-- Adapter
Adapter --> Adaptee : adaptee
Note
If the UML above is not rendering correctly, you can view the diagram from the adapter_uml.png
file.
- The Adapter Pattern is ideal for bridging incompatible interfaces.
- It enables flexibility and code reuse without modifying existing code.
- Use it when you need to integrate systems with incompatible interfaces.