Sobes.tech
Junior — Middle

What is the main function of the Adapter pattern in software design?

sobes.tech AI

Answer from AI

The main function of the Adapter pattern is to ensure compatibility between the interfaces of two unrelated classes, allowing them to work together. The Adapter acts as a "translator," transforming the interface of one class into the interface expected by the client.

For example, if you have a class with a certain method, and the client expects a different method, the Adapter implements the required interface and internally calls the methods of the adaptable class.

Example in Java:

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

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

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

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

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

Thus, the Adapter pattern allows you to use existing classes with incompatible interfaces without changing their code.

What is the main function of the Adapter pattern in… - sobes.tech