Sobes.tech
Junior — Middle

What is the purpose and application of the Adapter design pattern in software development?

sobes.tech AI

Answer from AI

The Adapter design pattern is used to convert the interface of one class into the interface expected by the client. This allows classes with incompatible interfaces to work together without changing their source code.

Application:

  • Integrating old code with new.
  • Ensuring compatibility between different libraries or modules.

Example in Java:

// Target interface
interface Target {
    void request();
}

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

// Adapter implementing the target interface and calling Adaptee's methods
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 target = new Adapter(adaptee);
        target.request(); // Calls specificRequest through the adapter
    }
}