Adapter Pattern

Category : Design Patterns | Sub Category : Structural design patterns | By Prasad Bonam Last updated: 2023-07-09 08:50:59 Viewed : 344


Adapter Pattern

The Adapter pattern is a structural design pattern that allows incompatible classes to work together by converting the interface of one class into another interface that the client expects. It acts as a bridge between two incompatible interfaces, enabling them to collaborate without modifying their existing code. Here is an example of implementing the Adapter pattern in Java:

java
// Target interface interface Target { void request(); } // Adaptee class class Adaptee { public void specificRequest() { System.out.println("Specific request called in Adaptee."); } } // Adapter class class Adapter implements Target { private Adaptee adaptee; public Adapter(Adaptee adaptee) { this.adaptee = adaptee; } @Override public void request() { adaptee.specificRequest(); } } // Client code public class Client { public static void main(String[] args) { Adaptee adaptee = new Adaptee(); Target target = new Adapter(adaptee); target.request(); // Output: Specific request called in Adaptee. } }

In this example:

  • The Target interface represents the interface expected by the client. It declares the request() method that the client uses to make requests.
  • The Adaptee class is an existing class with a different interface. It has the specificRequest() method that the client cannot directly use.
  • The Adapter class implements the Target interface and acts as a bridge between the Target interface and the Adaptee class. It contains a reference to the Adaptee class and adapts its interface to the Target interface.
  • In the Adapter class, the request() method is implemented by invoking the specificRequest() method of the Adaptee class.
  • The client code creates an instance of the Adaptee class and passes it to the Adapter constructor. It then interacts with the Target interface, which internally delegates the request to the Adaptee object.

By using the Adapter pattern, you can integrate existing classes or third-party libraries that have incompatible interfaces with your codebase. The adapter acts as a translator, enabling the client code to work seamlessly with the adapted interface. This pattern promotes code reusability, maintainability, and flexibility.

Search
Related Articles

Leave a Comment: