Sobes.tech
Junior — Middle

Can you explain the principle of the adapter pattern and in what cases it is used?

sobes.tech AI

Answer from AI

The Adapter pattern is used to "adapt" the interface of one class to the interface expected by the client. This allows classes with incompatible interfaces to work together.

Working principle:

  • There is a class with a specific interface (Adaptee).
  • There is a client expecting a different interface (Target).
  • The adapter implements the Target interface and contains an Adaptee object.
  • Client calls are redirected by the adapter to the Adaptee's methods, possibly with data transformation.

It is used when integrating old code or third-party libraries with incompatible interfaces without changing them.

Example in Java:

// Interface expected by the client
interface Target {
    void request();
}

// Class with incompatible interface
class Adaptee {
    void specificRequest() {
        System.out.println("Calling specific method");
    }
}

// Adapter
class Adapter implements Target {
    private Adaptee adaptee;

    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    @Override
    public void request() {
        adaptee.specificRequest();
    }
}

// Usage
public class Main {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Target adapter = new Adapter(adaptee);
        adapter.request(); // Calls specificRequest through the adapter
    }
}