Adapter pattern
In software engineering, the adapter pattern is a software design pattern that allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code.
An example is an adapter that converts the interface of a Document Object Model of an XML document into a tree structure that can be displayed.
Overview
The adapter design pattern is one of the twenty-three well-known Gang of Four design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.The adapter design pattern solves problems like:
- How can a class be reused that does not have an interface that a client requires?
- How can classes that have incompatible interfaces work together?
- How can an alternative interface be provided for a class?
The adapter design pattern describes how to solve such problems:
- Define a separate
adapterclass that converts the interface of a class into another interface clients require. - Work through an
adapterto work with classes that do not have the required interface.
adapter that adapts the interface of an class without changing it.Clients don't know whether they work with a
target class directly or through an adapter with a class that does not have the target interface.See also the UML class diagram below.
Definition
An adapter allows two incompatible interfaces to work together. This is the real-world definition for an adapter. Interfaces may be incompatible, but the inner functionality should suit the need. The adapter design pattern allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients.Usage
An adapter can be used when the wrapper must respect a particular interface and must support polymorphic behavior. Alternatively, a decorator pattern makes it possible to add or alter behavior of an interface at run-time, and a facade pattern is used when an easier or simpler interface to an underlying object is desired.| Pattern | Intent |
| Adapter or wrapper | Converts one interface to another so that it matches what the client is expecting |
| Decorator | Dynamically adds responsibility to the interface by wrapping the original code |
| Delegation | Support "composition over inheritance" |
| Facade | Provides a simplified interface |
Structure
UML class diagram
In the above UML class diagram, theclient class that requires a target interface cannot reuse the adaptee class directly because its interface doesn't conform to the target interface.Instead, the
client works through an adapter class that implements the target interface in terms of adaptee:- The
object adapterway implements thetargetinterface by delegating to anadapteeobject at run-time. - The
class adapterway implements thetargetinterface by inheriting from anadapteeclass at compile-time.
Object adapter pattern
In this adapter pattern, the adapter contains an instance of the class it wraps. In this situation, the adapter makes calls to the instance of the wrapped object.Class adapter pattern
This adapter pattern uses multiple polymorphic interfaces implementing or inheriting both the interface that is expected and the interface that is pre-existing. It is typical for the expected interface to be created as a pure interface class, especially in languages such as Java that do not support multiple inheritance of classes.A further form of runtime adapter pattern
Motivation from compile time solution
It is desired for to supply with some data, let us suppose some data. A compile time solution is:classB.setStringData);
However, suppose that the format of the string data must be varied. A compile time solution is to use inheritance:
public class Format1ClassA extends ClassA
and perhaps create the correctly "formatting" object at runtime by means of the factory pattern.
Run-time adapter solution
A solution using "adapters" proceeds as follows:Implementation of the adapter pattern
When implementing the adapter pattern, for clarity, one can apply the class name to the provider implementation; for example,. It should have a constructor method with an adaptee class variable as a parameter. This parameter will be passed to an instance member of. When the clientMethod is called, it will have access to the adaptee instance that allows for accessing the required data of the adaptee and performing operations on that data that generates the desired output.Java
package org.wikipedia.examples;
interface ILightningPhone
interface IMicroUsbPhone
class Iphone implements ILightningPhone
class Android implements IMicroUsbPhone
/* exposing the target interface while wrapping source object */
class LightningToMicroUsbAdapter implements IMicroUsbPhone
public class AdapterDemo
Output
Recharging android with MicroUsb
MicroUsb connected
Recharge started
Recharge finished
Recharging iPhone with Lightning
Lightning connected
Recharge started
Recharge finished
Recharging iPhone with MicroUsb
MicroUsb connected
Lightning connected
Recharge started
Recharge finished
Python
"""
Adapter pattern example.
"""
from abc import ABCMeta, abstractmethod
from typing import NoReturn
RECHARGE: list =
POWER_ADAPTERS: dict =
CONNECTED_MSG: str = " connected."
CONNECT_FIRST_MSG: str = "Connect first."
class RechargeTemplate:
@abstractmethod
def recharge -> NoReturn:
raise NotImplementedError
class FormatIPhone:
@abstractmethod
def use_lightning -> NoReturn:
raise NotImplementedError
class FormatAndroid:
@abstractmethod
def use_micro_usb -> NoReturn:
raise NotImplementedError
class IPhone:
__name__: str = "iPhone"
def __init__:
self.connector: bool = False
def use_lightning -> None:
self.connector = True
def recharge -> None:
if self.connector:
for state in RECHARGE:
else:
class Android:
__name__: str = "Android"
def __init__ -> None:
self.connector: bool = False
def use_micro_usb -> None:
self.connector = True
def recharge -> None:
if self.connector:
for state in RECHARGE:
else:
class IPhoneAdapter:
def __init__ -> None:
self.mobile: FormatAndroid = mobile
def recharge -> None:
self.mobile.recharge
def use_micro_usb -> None:
self.mobile.use_lightning
class AndroidRecharger:
def __init__ -> None:
self.phone: Android = Android
self.phone.use_micro_usb
self.phone.recharge
class IPhoneMicroUSBRecharger:
def __init__ -> None:
self.phone: IPhone = IPhone
self.phone_adapter: IPhoneAdapter = IPhoneAdapter
self.phone_adapter.use_micro_usb
self.phone_adapter.recharge
class IPhoneRecharger:
def __init__ -> None:
self.phone: IPhone = IPhone
self.phone.use_lightning
self.phone.recharge
AndroidRecharger
IPhoneMicroUSBRecharger
IPhoneRecharger
C#
namespace Wikipedia.Examples;
using System;
interface ILightningPhone
interface IUsbPhone
sealed class AndroidPhone : IUsbPhone
sealed class ApplePhone : ILightningPhone
sealed class LightningToUsbAdapter : IUsbPhone
public class AdapterDemo
Apple phone connected.
Apple phone recharging.