Skip to content

Adapter Pattern in Java with examples

Posted on:February 14, 2023 at 04:20 PM

The Adapter Pattern is a design pattern in software development that allows two incompatible interfaces to work together. This pattern is used when an existing class cannot be modified but needs to be integrated with other classes that expect a different interface. The adapter pattern solves this problem by creating an adapter class that acts as a bridge between the two interfaces, allowing the classes to work together.

Understanding the Adapter Pattern in Java

In Java, the adapter pattern can be implemented in two ways: class adapter and object adapter. The class adapter pattern uses inheritance to adapt the target interface, while the object adapter pattern uses composition to adapt the target interface.

Here’s a simple example of the class adapter pattern in Java:

interface Target {
    void request();
}

class Adaptee {
    void specificRequest() {
        System.out.println("Specific request");
    }
}

class ClassAdapter extends Adaptee implements Target {
    @Override
    public void request() {
        specificRequest();
    }
}

public class Main {
    public static void main(String[] args) {
        Target target = new ClassAdapter();
        target.request();
    }
}

And here’s a simple example of the object adapter pattern in Java:

interface Target {
    void request();
}

class Adaptee {
    void specificRequest() {
        System.out.println("Specific request");
    }
}

class ObjectAdapter implements Target {
private Adaptee adaptee;

    ObjectAdapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

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

public class Main {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Target target = new ObjectAdapter(adaptee);
        target.request();
    }
}

Benefits of Using the Adapter Pattern in Java

The adapter pattern provides a number of benefits, including:

When to Use the Adapter Pattern in Java

The adapter pattern should be used when:

Conclusion

The Adapter Pattern is a useful design pattern in Java that allows two incompatible interfaces to work together. By creating an adapter class that acts as a bridge between the two interfaces, the adapter pattern makes it possible to reuse existing code and add new functionality to existing systems. Whether you’re working with class adapters or object adapters, the adapter pattern provides a flexible and reusable solution for integrating different systems and components.