Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Bridge Method - Python Design Patterns
Next article icon

Adapter Method – Python Design Patterns

Last Updated : 11 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
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())) 

Output
A MotorCycle is a TwoWheeler vehicle A Truck is a EightWheeler vehicle A Car is a FourWheeler vehicle 

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



Next Article
Bridge Method - Python Design Patterns
author
chaudhary_19
Improve
Article Tags :
  • Design Pattern
  • Python
  • System Design
  • python-design-pattern
Practice Tags :
  • python

Similar Reads

  • Python Design Patterns Tutorial
    Design patterns in Python are communicating objects and classes that are customized to solve a general design problem in a particular context. Software design patterns are general, reusable solutions to common problems that arise during the design and development of software. They represent best pra
    8 min read
  • Creational Software Design Patterns in Python

    • Factory Method - Python Design Patterns
      Factory Method is a Creational Design Pattern that allows an interface or a class to create an object, but lets subclasses decide which class or object to instantiate. Using the Factory method, we have the best ways to create an object. Here, objects are created without exposing the logic to the cli
      4 min read
    • Abstract Factory Method - Python Design Patterns
      Abstract Factory Method is a Creational Design pattern that allows you to produce the families of related objects without specifying their concrete classes. Using the abstract factory method, we have the easiest ways to produce a similar type of many objects. It provides a way to encapsulate a group
      4 min read
    • Builder Method - Python Design Patterns
      Builder Method is a Creation Design Pattern which aims to "Separate the construction of a complex object from its representation so that the same construction process can create different representations." It allows you to construct complex objects step by step. Here using the same construction code
      5 min read
    • Prototype Method Design Pattern in Python
      The Prototype Method Design Pattern in Python enables the creation of new objects by cloning existing ones, promoting efficient object creation and reducing overhead. This pattern is particularly useful when the cost of creating a new object is high and when an object's initial state or configuratio
      6 min read
    • Singleton Method - Python Design Patterns
      Prerequisite: Singleton Design pattern | Introduction What is Singleton Method in PythonSingleton Method is a type of Creational Design pattern and is one of the simplest design patterns available to us. It is a way to provide one and only one object of a particular type. It involves only one class
      5 min read
    • Structural Software Design Patterns in Python

      • Adapter Method - Python Design Patterns
        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 cre
        4 min read
      • Bridge Method - Python Design Patterns
        The bridge method is a Structural Design Pattern that allows us to separate the Implementation Specific Abstractions and Implementation Independent Abstractions from each other and can be developed considering as single entities.The bridge Method is always considered as one of the best methods to or
        5 min read
      geeksforgeeks-footer-logo
      Corporate & Communications Address:
      A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
      Registered Address:
      K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
      GFG App on Play Store GFG App on App Store
      Advertise with us
      • Company
      • About Us
      • Legal
      • Privacy Policy
      • In Media
      • Contact Us
      • Advertise with us
      • GFG Corporate Solution
      • Placement Training Program
      • Languages
      • Python
      • Java
      • C++
      • PHP
      • GoLang
      • SQL
      • R Language
      • Android Tutorial
      • Tutorials Archive
      • DSA
      • Data Structures
      • Algorithms
      • DSA for Beginners
      • Basic DSA Problems
      • DSA Roadmap
      • Top 100 DSA Interview Problems
      • DSA Roadmap by Sandeep Jain
      • All Cheat Sheets
      • Data Science & ML
      • Data Science With Python
      • Data Science For Beginner
      • Machine Learning
      • ML Maths
      • Data Visualisation
      • Pandas
      • NumPy
      • NLP
      • Deep Learning
      • Web Technologies
      • HTML
      • CSS
      • JavaScript
      • TypeScript
      • ReactJS
      • NextJS
      • Bootstrap
      • Web Design
      • Python Tutorial
      • Python Programming Examples
      • Python Projects
      • Python Tkinter
      • Python Web Scraping
      • OpenCV Tutorial
      • Python Interview Question
      • Django
      • Computer Science
      • Operating Systems
      • Computer Network
      • Database Management System
      • Software Engineering
      • Digital Logic Design
      • Engineering Maths
      • Software Development
      • Software Testing
      • DevOps
      • Git
      • Linux
      • AWS
      • Docker
      • Kubernetes
      • Azure
      • GCP
      • DevOps Roadmap
      • System Design
      • High Level Design
      • Low Level Design
      • UML Diagrams
      • Interview Guide
      • Design Patterns
      • OOAD
      • System Design Bootcamp
      • Interview Questions
      • Inteview Preparation
      • Competitive Programming
      • Top DS or Algo for CP
      • Company-Wise Recruitment Process
      • Company-Wise Preparation
      • Aptitude Preparation
      • Puzzles
      • School Subjects
      • Mathematics
      • Physics
      • Chemistry
      • Biology
      • Social Science
      • English Grammar
      • Commerce
      • World GK
      • GeeksforGeeks Videos
      • DSA
      • Python
      • Java
      • C++
      • Web Development
      • Data Science
      • CS Subjects
      @GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
      We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
      Lightbox
      Improvement
      Suggest Changes
      Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
      geeksforgeeks-suggest-icon
      Create Improvement
      Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
      geeksforgeeks-improvement-icon
      Suggest Changes
      min 4 words, max Words Limit:1000

      Thank You!

      Your suggestions are valuable to us.

      What kind of Experience do you want to share?

      Interview Experiences
      Admission Experiences
      Career Journeys
      Work Experiences
      Campus Experiences
      Competitive Exam Experiences