Adapter Pattern

Adapter Pattern

Welcome to the first lesson of the course - the Adapter pattern! The Adapter pattern allows objects with incompatible interfaces to work together. It acts as a bridge between two different interfaces. This lesson will help you understand and implement the Adapter pattern in Java.

What You Will Learn

In this lesson, you will learn:

  • The basic concept of the Adapter pattern.
  • How to implement the Adapter pattern with practical code examples.
  • Why the Adapter pattern is useful in software design.

Implementing the Adapter Pattern

In this lesson, we will use an example involving Usb and MicroUsb connections to demonstrate the Adapter pattern. In this example, the problem is a device with a MicroUsb interface that needs to be used where a Usb interface is expected.

  • Target (Usb Interface): This is the interface the client code expects. It defines the method connectWithUsbCable.

  • Adaptee (MicroUsb Class): This is the existing class with an incompatible interface that needs to be adapted. It has the method connectWithMicroUsbCable.

  • Adapter: This is the class that bridges the gap between the Usb interface and the MicroUsb class. The Adapter implements the Usb interface and internally uses an instance of the MicroUsb class to translate the connectWithUsbCable call to connectWithMicroUsbCable.

By implementing the Adapter pattern, the MicroUsb device can now be used where a Usb interface is expected without modifying the existing client code or the MicroUsb class.

The Adapter pattern will help us solve this problem by creating a bridge between these incompatible interfaces so that they can work together seamlessly.

Step 1: Define the Target Interface

First, we define an interface that the client expects to interact with. This is our target interface.

public interface Usb {
    void connectWithUsbCable();
}

In this example, Usb is the target interface. It declares the connectWithUsbCable method, which the client expects.

Step 2: Create the Adaptee

The adaptee is the existing class with an incompatible interface that needs to be adapted.

public class MicroUsb {
    public void connectWithMicroUsbCable() {
        System.out.println("Connected with MicroUSB cable.");
    }
}

Here, MicroUsb is the adaptee. It has a method connectWithMicroUsbCable, which is not compatible with Usb.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal