Skip to content

Latest commit

 

History

History
58 lines (37 loc) · 2.07 KB

File metadata and controls

58 lines (37 loc) · 2.07 KB

Adapter Pattern

Overview

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.

Pattern Structure

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.

Key Concepts

  • 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

Examples

SimpleAdapter

Demonstrates adapting a Turkey to work as a Duck.

See the SimpleAdapter README for details on compiling and running.

How to Compile

From the parent directory of AdapterPattern:

javac -d out AdapterPattern/SimpleAdapter/*.java

How to Run

java -cp out AdapterPattern.SimpleAdapter.DuckTestDrive

Benefits of the Adapter Pattern

  • 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

When to Use

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