What is Adapters Design Pattern

Design patterns are reusable solutions to common problems that occur in software design. The Adapter pattern is one such pattern that helps solve the problem of incompatible interfaces between classes. In this article, we will discuss the Adapter pattern in detail, including its use, implementation in Java, C, and Python, and its advantages and disadvantages.

What is the Adapter Design Pattern?

The Adapter pattern is a structural pattern that allows two incompatible interfaces to work together. It involves creating an intermediary object that maps the interface of one class to another interface. This allows classes with incompatible interfaces to work together seamlessly.

Use of the Adapter Design Pattern:

The Adapter pattern is useful in the following situations:

1. When you want to use an existing class, but its interface is not compatible with the rest of the system.

2. When you want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that do not necessarily have compatible interfaces.

3. When you want to provide a simplified version of an interface to a client.

The Adapter pattern involves four components:

1. Target Interface: This is the interface that the client expects.

2. Adaptee Class: This is the class that needs to be adapted to work with the Target Interface.

3. Adapter Class: This is the class that adapts the Adaptee Class to the Target Interface.

4. Client Class: This is the class that uses the Target Interface.

To implement the Adapter design pattern, you need to create an adapter class that implements the Target interface and wraps the Adaptee. The adapter class then calls the appropriate methods of the Adaptee to implement the methods of the Target interface.

Let’s look at an example to understand the implementation of the Adapter design pattern. Suppose you have a music player that can play MP3 files, but you want it to also play WMA files. However, the music player does not support the WMA format. To solve this problem, you can use the Adapter design pattern as follows:

  1. Target: MusicPlayer interface with methods playMP3() and playWMA().

  2. Adaptee: WMAPlayer class with method playWMA().

  3. Adapter: WMAMusicAdapter class that implements the MusicPlayer interface and wraps the WMAPlayer. The adapter class calls the playWMA() method of the WMAPlayer to implement the playWMA() method of the MusicPlayer interface. The playMP3() method of the MusicPlayer interface is implemented directly in the adapter class.

  4. Client: MusicPlayerClient class that uses the MusicPlayer interface.

Implementation of Adapter Pattern in Java

Let’s look at an example to understand how to implement the Adapter pattern in Java. Suppose you have an application that needs to display a list of employees. The Employee class has the properties name, id, and email, but the application needs to display the employee’s name and email only.

Here’s how you can implement the Adapter pattern in Java:

1. Target Interface: Create an interface with the methods that the client expects. In this case, create an interface called EmployeeList that has a method called displayList().

public interface EmployeeList {
     public void displayList();
}

2. Adaptee Class: Create the Adaptee class that needs to be adapted. In this case, create a class called Employee with the properties name, id, and email.

public class Employee {
    private String name;
    private int id;
    private String email;

    public Employee(String name, int id, String email) {
        this.name = name;
        this.id = id;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public int getId() {
        return id;
    }

    public String getEmail() {
        return email;
    }
}

3. Adapter Class: Create the Adapter class that adapts the Adaptee class to the Target Interface. In this case, create a class called EmployeeListAdapter that implements the EmployeeList interface and wraps the Employee class.

public class EmployeeListAdapter implements EmployeeList {
    private List<Employee> employeeList;

    public EmployeeListAdapter(List<Employee> employeeList) {
        this.employeeList = employeeList;
    }

    public void displayList() {
        for (Employee employee : employeeList) {
            System.out.println("Name: " + employee.getName() + ", Email: " + employee.getEmail());
        }
    }
}

4. Client Class: Finally, create the Client class that uses the Target Interface. In this case, create a class called Client that creates a list of employees and uses the EmployeeListAdapter to display the list.

import java.util.ArrayList;
import java.util.List;

public class Client {
    public static void main(String[] args) {
        List<Employee> employeeList = new ArrayList<>();
        employeeList.add(new Employee("John Doe", 1, "[email protected]"));
        employeeList.add(new Employee("Jane Doe", 2, "[email protected]"));
      EmployeeList employeeListAdapter = new 
         EmployeeListAdapter(employeeList);
         employeeListAdapter.displayList();
   }
}

In this example, the EmployeeListAdapter class adapts the Employee class to the EmployeeList interface, allowing the client to display a simplified version of the employee list.

Implementation of Adapter Pattern in C

Let’s look at an example to understand how to implement the Adapter pattern in C. Suppose you have an application that needs to calculate the area of a rectangle. The Rectangle struct has the properties width and height, but the application needs to calculate the area using the CalculateArea() function.

Here’s how you can implement the Adapter pattern in C:

1. Target Interface: Create an interface with the methods that the client expects. In this case, create a struct called RectangleArea with a function pointer called CalculateArea.

typedef struct RectangleArea {
int (*CalculateArea)(struct RectangleArea *rect);
} RectangleArea;

2. Adaptee Class: Create the Adaptee struct that needs to be adapted. In this case, create a struct called Rectangle with the properties width and height.

typedef struct Rectangle {
  int width;
  int height;
} Rectangle;

3. Adapter Class: Create the Adapter struct that adapts the Adaptee struct to the Target Interface. In this case, create a struct called RectangleAdapter that implements the RectangleArea interface and wraps the Rectangle struct.

int CalculateRectangleArea(RectangleArea *rectArea) {
Rectangle *rect = (Rectangle *) rectArea;
return rect->width * rect->height;
}

RectangleArea *CreateRectangleAdapter(Rectangle *rect) {
RectangleArea *rectArea = (RectangleArea *) malloc(sizeof(RectangleArea));
rectArea->CalculateArea = CalculateRectangleArea;
memcpy((void *) rectArea + sizeof(int *), (void *) rect, sizeof(Rectangle));
return rectArea;
}

4. Client Code: Finally, create the client code that uses the Target Interface. In this case, create a function called DisplayRectangleArea that creates a Rectangle struct, creates a RectangleAdapter using the CreateRectangleAdapter function, and calculates the area using the CalculateArea function.

void DisplayRectangleArea() {
Rectangle rect = {10, 20};
RectangleArea *rectArea = CreateRectangleAdapter(&rect);
int area = rectArea->CalculateArea(rectArea);
printf("Area: %d\n", area);
free(rectArea);
}

int main() {
DisplayRectangleArea();
return 0;
}

In this example, the RectangleAdapter struct adapts the Rectangle struct to the RectangleArea interface, allowing the client to calculate the area using the CalculateArea function.

Implementation of Adapter Pattern in Python

Let’s look at an example to understand how to implement the Adapter pattern in Python. Suppose you have an application that needs to display the weather forecast. The Weather class has the properties temperature, pressure, and humidity, but the application needs to display the temperature only.

Here’s how you can implement the Adapter pattern in Python:

1. Target Interface: Create an interface with the methods that the client expects. In this case, create a class called TemperatureDisplay with a method called displayTemperature.

class TemperatureDisplay:
    def displayTemperature(self):
          pass

2. Adaptee Class: Create the Adaptee class that needs to be adapted. In this case, create a class called Weather with the properties temperature, pressure, and humidity.

class Weather:
    def __init__(self, temperature, pressure, humidity):
        self.temperature = temperature
        self.pressure = pressure
        self.humidity = humidity

3. Adapter Class: Create the Adapter class that adapts the Adaptee class to the Target Interface. In this case, create a class called TemperatureAdapter that implements the TemperatureDisplay interface and wraps the Weather class.

class TemperatureAdapter(TemperatureDisplay):
    def __init__(self, weather):
        self.weather = weather
    
    def displayTemperature(self):
        print("Temperature: " + str(self.weather.temperature) + " degrees Celsius")

4. Client Code: Finally, create the client code that uses the Target Interface. In this case, create a function called DisplayTemperature that creates a Weather object, creates a TemperatureAdapter using the TemperatureAdapter constructor, and displays the temperature using the displayTemperature method.

def DisplayTemperature():
    weather = Weather(25, 1013, 70)
    temperatureAdapter = TemperatureAdapter(weather)
    temperatureAdapter.displayTemperature()

DisplayTemperature()

In this example, the TemperatureAdapter class adapts the Weather class to the TemperatureDisplay interface, allowing the client to display the temperature only.

Advantages of Adapter Pattern

1. Reusability: The Adapter pattern allows the reuse of existing classes and interfaces, which saves time and effort in development.

2. Flexibility: The Adapter pattern makes it easy to add new functionality to existing classes and interfaces without modifying the existing code.

3. Separation of Concerns: The Adapter pattern separates the concerns of the client and the adaptee, making the code more maintainable and easier to understand.

4. Code Maintenance: The Adapter pattern makes it easy to maintain the code, as changes to the adaptee do not affect the client code.

Disadvantages of Adapter Pattern

1. Complexity: The Adapter pattern can add complexity to the code, as it requires the creation of additional classes and interfaces.

2. Performance Overhead: The Adapter pattern can introduce performance overhead, as additional code is required to map the adaptee interface to the target interface.

3. Overuse: The Adapter pattern should be used judiciously, as overuse can lead to code bloat and reduced performance.

Conclusion

The Adapter pattern is a design pattern that allows the adaptation of existing classes and interfaces to meet the requirements of new clients. It is a powerful tool for developers to reuse existing code, add new functionality, and maintain code over time. The Adapter pattern is implemented in many programming languages, including Java, C, and Python. While the Adapter pattern has advantages such as reusability, flexibility, and separation of concerns, it also has disadvantages such as complexity, performance overhead, and overuse. Developers should use the Adapter pattern judiciously to ensure that it adds value to their codebase.

What is Adapters Design Pattern

Published on 04-Jul-2024 21:48:12

You may also like this!