In
software engineering
Software engineering is a systematic engineering approach to software development.
A software engineer is a person who applies the principles of software engineering to design, develop, maintain, test, and evaluate computer software. The term '' ...
, the adapter pattern is a
software design pattern
In software engineering, a software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code ...
(also known as
wrapper, an alternative naming shared with the
decorator pattern
In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class. The decorator pattern is often ...
) that allows the
interface
Interface or interfacing may refer to:
Academic journals
* ''Interface'' (journal), by the Electrochemical Society
* '' Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Linguistics''
* '' Int ...
of an existing
class
Class or The Class may refer to:
Common uses not otherwise categorized
* Class (biology), a taxonomic rank
* Class (knowledge representation), a collection of individuals or objects
* Class (philosophy), an analytical concept used differentl ...
to be used as another interface.
It is often used to make existing classes work with others without modifying their
source code
In computing, source code, or simply code, is any collection of code, with or without comments, written using a human-readable programming language, usually as plain text. The source code of a program is specially designed to facilitate the wo ...
.
An example is an adapter that converts the interface of a
Document Object Model
The Document Object Model (DOM) is a cross-platform and language-independent interface that treats an XML or HTML document as a tree structure wherein each node is an object representing a part of the document. The DOM represents a document wi ...
of an
XML
Extensible Markup Language (XML) is a markup language and file format for storing, transmitting, and reconstructing arbitrary data. It defines a set of rules for encoding documents in a format that is both human-readable and machine-readable ...
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?
Often an (already existing) class can't be reused only because its interface doesn't conform to the interface clients require.
The adapter design pattern describes how to solve such problems:
* Define a separate
adapter
class that converts the (incompatible) interface of a class (
adaptee
) into another interface (
target
) clients require.
* Work through an
adapter
to work with (reuse) classes that do not have the required interface.
The key idea in this pattern is to work through a separate
adapter
that adapts the interface of an (already existing) 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 makes it possible to add or alter behavior of an interface at run-time, and a
facade is used when an easier or simpler interface to an underlying object is desired.
Structure
UML class diagram
In the above
UML
The Unified Modeling Language (UML) is a general-purpose, developmental modeling language in the field of software engineering that is intended to provide a standard way to visualize the design of a system.
The creation of UML was originally m ...
class diagram
In software engineering, a class diagram in the Unified Modeling Language (UML) is a type of static structure diagram that describes the structure of a system by showing the system's classes, their attributes, operations (or methods), and the rela ...
, the
client
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 adapter
way implements the
target
interface by delegating to an
adaptee
object at run-time (
adaptee.specificOperation()
).
* The
class adapter
way implements the
target
interface by inheriting from an
adaptee
class at compile-time (
specificOperation()
).
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
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not exist at any particular time or place
** Physical object, an identifiable collection of matter
* Goal, an ...
.
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
Interface or interfacing may refer to:
Academic journals
* ''Interface'' (journal), by the Electrochemical Society
* '' Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Linguistics''
* '' Int ...
class, especially in
languages such as
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
(before JDK 1.8) that do not support
multiple inheritance
Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class. It is distinct from single inheritance, where an object or ...
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(classA.getStringData());
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
In object-oriented programming, a factory is an object for creating other objects; formally, it is a function or method that returns objects of a varying prototype or class from some method call, which is assumed to be "new". More broadly, a su ...
.
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
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
NOT_IMPLEMENTED = "You should implement this."
RECHARGE = Recharge started.", "Recharge finished."
POWER_ADAPTERS =
CONNECTED = " connected."
CONNECT_FIRST = "Connect first."
class RechargeTemplate(metaclass=ABCMeta):
@abstractmethod
def recharge(self):
raise NotImplementedError(NOT_IMPLEMENTED)
class FormatIPhone(RechargeTemplate):
@abstractmethod
def use_lightning(self):
raise NotImplementedError(NOT_IMPLEMENTED)
class FormatAndroid(RechargeTemplate):
@abstractmethod
def use_micro_usb(self):
raise NotImplementedError(NOT_IMPLEMENTED)
class IPhone(FormatIPhone):
__name__ = "iPhone"
def __init__(self):
self.connector = False
def use_lightning(self):
self.connector = True
print(CONNECTED.format(POWER_ADAPTERS elf.__name__)
def recharge(self):
if self.connector:
for state in RECHARGE:
print(state)
else:
print(CONNECT_FIRST.format(POWER_ADAPTERS elf.__name__)
class Android(FormatAndroid):
__name__ = "Android"
def __init__(self):
self.connector = False
def use_micro_usb(self):
self.connector = True
print(CONNECTED.format(POWER_ADAPTERS elf.__name__)
def recharge(self):
if self.connector:
for state in RECHARGE:
print(state)
else:
print(CONNECT_FIRST.format(POWER_ADAPTERS elf.__name__)
class IPhoneAdapter(FormatAndroid):
def __init__(self, mobile):
self.mobile = mobile
def recharge(self):
self.mobile.recharge()
def use_micro_usb(self):
print(CONNECTED.format(POWER_ADAPTERS Android")
self.mobile.use_lightning()
class AndroidRecharger:
def __init__(self):
self.phone = Android()
self.phone.use_micro_usb()
self.phone.recharge()
class IPhoneMicroUSBRecharger:
def __init__(self):
self.phone = IPhone()
self.phone_adapter = IPhoneAdapter(self.phone)
self.phone_adapter.use_micro_usb()
self.phone_adapter.recharge()
class IPhoneRecharger:
def __init__(self):
self.phone = IPhone()
self.phone.use_lightning()
self.phone.recharge()
print("Recharging Android with MicroUSB recharger.")
AndroidRecharger()
print()
print("Recharging iPhone with MicroUSB using adapter pattern.")
IPhoneMicroUSBRecharger()
print()
print("Recharging iPhone with iPhone recharger.")
IPhoneRecharger()
C#
public interface ILightningPhone
public interface IUsbPhone
public sealed class AndroidPhone : IUsbPhone
public sealed class ApplePhone : ILightningPhone
public sealed class LightningToUsbAdapter : IUsbPhone
public void Main()
Output:
Apple phone connected.
Adapter cable connected.
Apple phone recharging.
See also
AdapterJava Design Patterns - Adapter
*
Delegation, strongly relevant to the object adapter pattern.
*
Dependency inversion principle
In object-oriented design, the dependency inversion principle is a specific methodology for loosely coupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-settin ...
, which can be thought of as applying the adapter pattern, when the high-level class defines its own (adapter) interface to the low-level module (implemented by an adaptee class).
*
Ports and adapters architecture
The hexagonal architecture, or ports and adapters architecture, is an architectural pattern used in software design. It aims at creating loosely coupled application components that can be easily connected to their software environment by means of ...
*
Shim
Shim may refer to:
* Shim (spacer), a thin and often tapered or wedged piece of material
** CPU shim, a spacer for a computer heat sink
** Shim (fencing), a device used in the sport fencing
** Shim (lock pick), a tool used to bypass padlocks
* Sh ...
*
Wrapper function
A wrapper function is a function (another word for a ''subroutine'') in a software library or a computer program whose main purpose is to call a second subroutine or a system call with little or no additional computation. Wrapper functions are u ...
*
Wrapper library
Wrapper libraries (or library wrappers) consist of a thin layer of code (a "shim") which translates a library's existing interface into a compatible interface. This is done for several reasons:
* To refine a poorly designed or complicated interfac ...
References
{{Design Patterns Patterns
Software design patterns
Articles with example Java code