Table of Contents
What is Adapter Mode?
When should I use adapter mode?
How to implement adapters in Python?
What is the difference between an adapter and an appearance mode?
Tips: Don't abuse the adapter
Home Backend Development Python Tutorial Adapter Pattern in Python

Adapter Pattern in Python

Aug 01, 2025 am 04:43 AM

Adapter mode is a structural design mode that allows incompatible interfaces to work together. It converts the interface of the class like a "translator", so that the old system connects with the new library without rewriting the logic. Applicable scenarios include reusing existing classes, unified subclass interfaces, encapsulating third-party APIs, etc. In the implementation, the target object is wrapped by creating an adapter class, calling its methods and converting the interface, such as adapting NewLogger to the OldLogger interface with LoggerAdapter. Unlike appearance mode, adapters focus on interface conversion, while appearance focuses on simplifying complex interfaces. Abuse should be avoided when using it and pay attention to clear naming.

Adapter Pattern in Python

Use adapter mode in Python, mainly to enable incompatible interfaces to work together . It is a type of structural design pattern and is often used to avoid large-scale modifications to existing code when system expansion or integration of third-party libraries.

Adapter Pattern in Python

What is Adapter Mode?

Simply put, the adapter pattern is like a "translator", converting the interface of one class into the interface expected by another class. In this way, even if the two classes cannot communicate directly, they can work together.

For example, if you have a logging module for the old system, you want to replace it with a new log library, but the interface of the new library is different from the old one. At this time, you can use an adapter to connect to both sides, instead of rewriting the entire calling logic.

Adapter Pattern in Python

When should I use adapter mode?

Adapter mode is suitable for these situations:

  • It is necessary to reuse existing classes, but its interface does not meet the current requirements
  • Want to introduce new interface implementation without affecting existing code
  • There are differences between multiple subclasses, and we also hope to unify the consistent interfaces that are exposed to the outside world.

Common scenarios include encapsulating third-party APIs, integrating different data formats, bridging new and old systems, etc.

Adapter Pattern in Python

How to implement adapters in Python?

Python's dynamic features make implementing adapters more flexible than static languages. Here is a simple example:

Suppose you have two classes:

 class OldLogger:
    def log_message(self, msg):
        print("OldLogger:", msg)

class NewLogger:
    def write_log(self, level, message):
        print(f"NewLogger [{level}]: {message}")

You want to replace OldLogger with NewLogger , but don't want to change all calls. You can write an adapter:

 class LoggerAdapter:
    def __init__(self, logger):
        self.logger = logger

    def log_message(self, msg):
        self.logger.write_log("INFO", msg)

Then when replacing, just need to do this:

 logger = LoggerAdapter(NewLogger())
logger.log_message("This is a log.")

This will keep the original call method unchanged and access new functions.


What is the difference between an adapter and an appearance mode?

This is also something that many people are prone to confusion. The main difference between the two is the purpose:

  • Adapter mode : The focus is on interface conversion , so that existing interfaces can be used compatible.
  • Appearance mode : The focus is on simplifying the interface and providing a unified high-level interface for a set of complex interfaces.

For example:

  • The adapter is like changing the socket connector for the plug
  • It looks like installing a master switch for a bunch of buttons

Therefore, although both are structural models, they are applicable to different occasions.


Tips: Don't abuse the adapter

Although the adapter is practical, there are some things to note:

  • Do not overuse it, otherwise it may cause system structure chaos
  • Try to be clear in the name so that you can tell at a glance that this is a "middle layer"
  • If the parameter order is just different, you can use a wrapper function instead of the complete adapter

Basically that's it. Adapters are not written every day, but they are indeed a very handy gadget when integrating the system or refactoring the code.

The above is the detailed content of Adapter Pattern in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1545
276
Completed python blockbuster online viewing entrance python free finished website collection Completed python blockbuster online viewing entrance python free finished website collection Jul 23, 2025 pm 12:36 PM

This article has selected several top Python "finished" project websites and high-level "blockbuster" learning resource portals for you. Whether you are looking for development inspiration, observing and learning master-level source code, or systematically improving your practical capabilities, these platforms are not to be missed and can help you grow into a Python master quickly.

python run shell command example python run shell command example Jul 26, 2025 am 07:50 AM

Use subprocess.run() to safely execute shell commands and capture output. It is recommended to pass parameters in lists to avoid injection risks; 2. When shell characteristics are required, you can set shell=True, but beware of command injection; 3. Use subprocess.Popen to realize real-time output processing; 4. Set check=True to throw exceptions when the command fails; 5. You can directly call chains to obtain output in a simple scenario; you should give priority to subprocess.run() in daily life to avoid using os.system() or deprecated modules. The above methods override the core usage of executing shell commands in Python.

python seaborn jointplot example python seaborn jointplot example Jul 26, 2025 am 08:11 AM

Use Seaborn's jointplot to quickly visualize the relationship and distribution between two variables; 2. The basic scatter plot is implemented by sns.jointplot(data=tips,x="total_bill",y="tip",kind="scatter"), the center is a scatter plot, and the histogram is displayed on the upper and lower and right sides; 3. Add regression lines and density information to a kind="reg", and combine marginal_kws to set the edge plot style; 4. When the data volume is large, it is recommended to use "hex"

python httpx async client example python httpx async client example Jul 29, 2025 am 01:08 AM

Use httpx.AsyncClient to efficiently initiate asynchronous HTTP requests. 1. Basic GET requests manage clients through asyncwith and use awaitclient.get to initiate non-blocking requests; 2. Combining asyncio.gather to combine with asyncio.gather can significantly improve performance, and the total time is equal to the slowest request; 3. Support custom headers, authentication, base_url and timeout settings; 4. Can send POST requests and carry JSON data; 5. Pay attention to avoid mixing synchronous asynchronous code. Proxy support needs to pay attention to back-end compatibility, which is suitable for crawlers or API aggregation and other scenarios.

python list to string conversion example python list to string conversion example Jul 26, 2025 am 08:00 AM

String lists can be merged with join() method, such as ''.join(words) to get "HelloworldfromPython"; 2. Number lists must be converted to strings with map(str, numbers) or [str(x)forxinnumbers] before joining; 3. Any type list can be directly converted to strings with brackets and quotes, suitable for debugging; 4. Custom formats can be implemented by generator expressions combined with join(), such as '|'.join(f"[{item}]"foriteminitems) output"[a]|[

Optimizing Python for Memory-Bound Operations Optimizing Python for Memory-Bound Operations Jul 28, 2025 am 03:22 AM

Pythoncanbeoptimizedformemory-boundoperationsbyreducingoverheadthroughgenerators,efficientdatastructures,andmanagingobjectlifetimes.First,usegeneratorsinsteadofliststoprocesslargedatasetsoneitematatime,avoidingloadingeverythingintomemory.Second,choos

python connect to sql server pyodbc example python connect to sql server pyodbc example Jul 30, 2025 am 02:53 AM

Install pyodbc: Use the pipinstallpyodbc command to install the library; 2. Connect SQLServer: Use the connection string containing DRIVER, SERVER, DATABASE, UID/PWD or Trusted_Connection through the pyodbc.connect() method, and support SQL authentication or Windows authentication respectively; 3. Check the installed driver: Run pyodbc.drivers() and filter the driver name containing 'SQLServer' to ensure that the correct driver name is used such as 'ODBCDriver17 for SQLServer'; 4. Key parameters of the connection string

python shutil rmtree example python shutil rmtree example Aug 01, 2025 am 05:47 AM

shutil.rmtree() is a function in Python that recursively deletes the entire directory tree. It can delete specified folders and all contents. 1. Basic usage: Use shutil.rmtree(path) to delete the directory, and you need to handle FileNotFoundError, PermissionError and other exceptions. 2. Practical application: You can clear folders containing subdirectories and files in one click, such as temporary data or cached directories. 3. Notes: The deletion operation is not restored; FileNotFoundError is thrown when the path does not exist; it may fail due to permissions or file occupation. 4. Optional parameters: Errors can be ignored by ignore_errors=True

See all articles