Open In App

Adapter Method – Python Design Patterns

Last Updated : 06 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Adapter method is a Structural Design Pattern which helps us in making the incompatible objects adaptable to each other. The Adapter method is one of the easiest methods to understand because we have a lot of real-life examples that show the analogy with it. The main purpose of this method is to create a bridge between two incompatible interfaces. This method provides a different interface for a class. We can more easily understand the concept by thinking about the Cable Adapter that allows us to charge a phone somewhere that has outlets in different shapes. Using this idea, we can integrate the classes that couldn’t be integrated due to interface incompatibility.

Problem without using the Adapter Method

Imagine you are creating an application that shows the data about all different types of vehicles present. It takes the data from APIs of different vehicle organizations in XML format and then displays the information. But suppose at some time you want to upgrade your application with a Machine Learning algorithms that work beautifully on the data and fetch the important data only. But there is a problem, it takes data in JSON format only. It will be a really poor approach to make changes in Machine Learning Algorithm so that it will take data in XML format.

Problem-Adapter-Method

Problem-Adapter-Method

Solution using Adapter Method

For solving the problem we defined above, We can use Adapter Method that helps by creating an Adapter object. To use an adapter in our code:

  1. Client should make a request to the adapter by calling a method on it using the target interface.
  2. Using the Adaptee interface, the Adapter should translate that request on the adaptee.
  3. Result of the call is received the client and he/she is unaware of the presence of the Adapter’s presence.
Python
# Dog - Cycle
# human - Truck
# car - Car

class MotorCycle:

    """Class for MotorCycle"""

    def __init__(self):
        self.name = "MotorCycle"

    def TwoWheeler(self):
        return "TwoWheeler"


class Truck:

    """Class for Truck"""

    def __init__(self):
        self.name = "Truck"

    def EightWheeler(self):
        return "EightWheeler"


class Car:

    """Class for Car"""

    def __init__(self):
        self.name = "Car"

    def FourWheeler(self):
        return "FourWheeler"

class Adapter:
    """
    Adapts an object by replacing methods.
    Usage:
    motorCycle = MotorCycle()
    motorCycle = Adapter(motorCycle, wheels = motorCycle.TwoWheeler)
    """

    def __init__(self, obj, **adapted_methods):
        """We set the adapted methods in the object's dict"""
        self.obj = obj
        self.__dict__.update(adapted_methods)

    def __getattr__(self, attr):
        """All non-adapted calls are passed to the object"""
        return getattr(self.obj, attr)

    def original_dict(self):
        """Print original object dict"""
        return self.obj.__dict__


""" main method """
if __name__ == "__main__":

    """list to store objects"""
    objects = []

    motorCycle = MotorCycle()
    objects.append(Adapter(motorCycle, wheels = motorCycle.TwoWheeler))

    truck = Truck()
    objects.append(Adapter(truck, wheels = truck.EightWheeler))

    car = Car()
    objects.append(Adapter(car, wheels = car.FourWheeler))

    for obj in objects:
       print("A {0} is a {1} vehicle".format(obj.name, obj.wheels()))

Class Diagram

Class diagram for the Adapter method which is a type of Structural Design pattern:

Adapter-method-class-diagram

Adapter-class-diagram

Advantages

  • Principle of Single Responsibility: We can achieve the principle of Single responsibility with Adapter Method because here we can separate the concrete code from the primary logic of the client.
  • Flexibility: Adapter Method helps in achieving the flexibility and reusability of the code.
  • Less complicated class: Our client class is not complicated by having to use a different interface and can use polymorphism to swap between different implementations of adapters.
  • Open/Closed principle: We can introduce the new adapter classes into the code without violating the Open/Closed principle.

Disadvantages

  • Complexity of the Code: As we have introduced the set of new classes, objects and interfaces, the complexity of or code definitely rises.
  • Adaptability: Most of the times, we require many adaptations with the adaptee chain to reach the compatibility what we want.

Applicability

  • To make classes and interfaces compatible : Adapter method is always used when we are in need to make certain classes compatible to communicate.
  • Relatable to Inheritance: When we want to reuse some piece of code i.e., classes and interfaces that lack some functionalities, it can be done using the Adapter Method.

Further read: Adapter Pattern in Java



Previous Article
Next Article

Similar Reads

Adapter Method | JavaScript Design Patterns
Adapter Pattern in JavaScript is a structural design pattern that allows you to make one interface or object work with another that has a different interface. It acts as a bridge, enabling the compatibility of two systems that would not naturally work together. Important Topics for the Adapter Method in JavaScript Design Patterns Use Cases of the A
8 min read
Difference Between the Facade, Proxy, Adapter, and Decorator Design Patterns
Understanding design patterns is crucial for software developers. Facade, Proxy, Adapter, and Decorator are key patterns that address different aspects of software design, from simplifying interfaces to enhancing functionality. This article explores their distinctions and practical applications in software development. Important Topics for Facade v
4 min read
Adapter Pattern | C++ Design Patterns
Adapter Pattern is a structural design pattern used to make two incompatible interfaces work together. It acts as a bridge between two incompatible interfaces, allowing them to collaborate without modifying their source code. This pattern is particularly useful when integrating legacy code or third-party libraries into your application. Important T
6 min read
Adapter Design Pattern
The Adapter design pattern is a structural pattern that allows the interface of an existing class to be used as another interface. It acts as a bridge between two incompatible interfaces, making them work together. This pattern involves a single class, known as the adapter, which is responsible for joining functionalities of independent or incompat
6 min read
Difference Between Architectural Style, Architectural Patterns and Design Patterns
Many software professionals think that architectural styles and patterns are the same. Sadly, some of the software developers don’t understand the difference between architectural patterns and design patterns. In this article, we're going to summarize the differences between them. According to MSDN, architectural styles and patterns are the same th
7 min read
Connectivity and Composition Patterns | Design Patterns for Cloud Native Applications
In cloud-native applications, the architectural design becomes a critical aspect, defining the success of the entire solution. Connectivity and composition patterns are fundamental design principles that dictate how different components within a cloud-native application communicate and collaborate. Let's delve deeper into the significance of these
9 min read
Difference Between Bridge Pattern and Adapter Pattern
The Bridge Pattern and the Adapter Pattern are structural design patterns in object-oriented software development that primarily target the flexibility and reusability of a design. These two patterns have different roles and are used in different scenarios to solve specific design issues. Important Topics for Bridge Pattern vs Adapter Pattern What
5 min read
Strategy Method Design Pattern | C++ Design Patterns
Strategy Pattern is a behavioral design pattern that defines a family of interchangeable algorithms and allows them to be used interchangeably within a context. This pattern enables the algorithm to be selected at runtime, providing flexibility and promoting code reusability. Important Topics for the Strategy Method in C++ Design Patterns Example o
4 min read
State Method Design Pattern | C++ Design Patterns
In software design, managing the behavior of an object according to its internal state is a common issue. The state pattern addresses this issue by allowing an object to alter its behavior every time its internal state changes. This pattern encapsulates each state in a separate class, which makes it easier to add new states and modify existing stat
7 min read
Template Method Design Pattern | C++ Design Patterns
Template Method Pattern introduces a template in a superclass that defines the steps of an algorithm. These steps may include both common tasks shared among subclasses and specific tasks that need customization. Subclasses then implement or override these steps to modify the algorithm according to their specific needs. Important Topics for Template
7 min read