The Adapter Pattern converts the interface of a class into another interface that clients expect. It allows classes to work together that couldn't otherwise because of incompatible interfaces.
The Adapter Pattern uses composition to wrap an adaptee with an altered interface. This lets you adapt an incompatible interface into one that clients expect.
- Target Interface: The interface that the client expects (e.g.,
Duck) - Adaptee: The class with an incompatible interface that needs adapting (e.g.,
Turkey) - Adapter: The class that implements the target interface and wraps the adaptee (e.g.,
TurkeyAdapter) - Client: The code that uses the target interface
Demonstrates adapting a Turkey to work as a Duck.
- Duck.java - Target interface
- Turkey.java - Adaptee interface
- TurkeyAdapter.java - Adapter implementation
- DuckTestDrive.java - Test driver
See the SimpleAdapter README for details on compiling and running.
From the parent directory of AdapterPattern:
javac -d out AdapterPattern/SimpleAdapter/*.javajava -cp out AdapterPattern.SimpleAdapter.DuckTestDrive- Reusability: Allows existing classes to be used with incompatible interfaces
- Flexibility: Client code works with the target interface, not specific implementations
- Single Responsibility: Separates interface conversion from business logic
- Open/Closed Principle: Can introduce new adapters without changing existing code
Use the Adapter Pattern when:
- You want to use an existing class but its interface doesn't match what you need
- You need to create a reusable class that cooperates with unrelated classes
- You need to use several existing subclasses but it's impractical to adapt their interface by subclassing each one