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 GoF 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:
Often an 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:
The key idea in this pattern is to work through a separate 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 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.
PatternIntent
Adapter or wrapperConverts one interface to another so that it matches what the client is expecting
DecoratorDynamically adds responsibility to the interface by wrapping the original code
DelegationSupport "composition over inheritance"
FacadeProvides a simplified interface

Structure

UML class diagram

In the above UML class diagram, 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:
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:
Define an intermediary "provider" interface, and write an implementation of that provider interface that wraps the source of the data, in this example, and outputs the data formatted as appropriate:

public interface StringProvider
public class ClassAFormat1 implements StringProvider

Write an adapter class that returns the specific implementation of the provider:

public class ClassAFormat1Adapter extends Adapter

Register the with a global registry, so that the can be looked up at runtime:

AdapterFactory.getInstance.registerAdapter;

In code, when wishing to transfer data from to, write:

Adapter adapter =
AdapterFactory.getInstance
.getAdapterFromTo;
StringProvider provider = adapter.adapt;
String string = provider.getStringData;
classB.setStringData;

or more concisely:

classB.setStringData
AdapterFactory.getInstance
.getAdapterFromTo
.adapt)
.getStringData);

The advantage can be seen in that, if it is desired to transfer the data in a second format, then look up the different adapter/provider:

Adapter adapter =
AdapterFactory.getInstance
.getAdapterFromTo;

And if it is desired to output the data from as, say, image data in :

Adapter adapter =
AdapterFactory.getInstance
.getAdapterFromTo;
ImageProvider provider = adapter.adapt;
classC.setImage);

In this way, the use of adapters and providers allows multiple "views" by and into without having to alter the class hierarchy. In general, it permits a mechanism for arbitrary data flows between objects that can be retrofitted to an existing object hierarchy.

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.

Crystal">Crystal (programming language)">Crystal


abstract class FormatIphone
getter connector
abstract def recharge
abstract def use_lightning
end
abstract class FormatAndroid
getter connector
abstract def recharge
abstract def use_micro_usb
end
class Iphone < FormatIphone
def initialize
@connector = false
end
def use_lightning
@connector = true
puts "Lightning connected"
end
def recharge
if @connector
puts "Recharge started"
puts "Recharge finished"
else
puts "Connect Lightning first"
Close
end
end
class Android < FormatAndroid
def initialize
@connector = false
end
def use_micro_usb
@connector = true
puts "MicroUsb connected"
end
def recharge
if @connector
puts "Recharge started"
puts "Recharge finished"
else
puts "Connect MicroUsb first"
end
end
end
class IphoneAdapter < FormatAndroid
private getter mobile : FormatIphone
def initialize
end
def recharge
@mobile.recharge
end
def use_micro_usb
puts "MicroUsb connected"
@mobile.use_lightning
end
end
class AndroidRecharger
def initialize
phone = Android.new
phone.use_micro_usb
phone.recharge
end
end
class IphoneMicroUsbRecharger
def initialize
phone = Iphone.new
phone_adapter = IphoneAdapter.new
phone_adapter.use_micro_usb
phone_adapter.recharge
end
end
class IphoneRecharger
def initialize
phone = Iphone.new
phone.use_lightning
phone.recharge
end
end
puts "Recharging android with MicroUsb Recharger"
AndroidRecharger.new
puts
puts "Recharging iPhone with MicroUsb using Adapter pattern"
IphoneMicroUsbRecharger.new
puts
puts "Recharging iPhone with iPhone Recharger"
IphoneRecharger.new

Output

Recharging android with MicroUsb Recharger
MicroUsb connected
Recharge started
Recharge finished
Recharging iPhone with MicroUsb using Adapter pattern
MicroUsb connected
Lightning connected
Recharge started
Recharge finished
Recharging iPhone with iPhone Recharger
Lightning connected
Recharge started
Recharge finished

Java


interface LightningPhone
interface MicroUsbPhone
class Iphone implements LightningPhone
class Android implements MicroUsbPhone
/* exposing the target interface while wrapping source object */
class LightningToMicroUsbAdapter implements MicroUsbPhone
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

Delphi


type
ILightningPhone = interface

procedure Recharge;
procedure UseLightning;
end;
type
IMicroUSBPhone = interface

procedure Recharge;
procedure UseMicroUSB;
end;
type
TIPhone = class
strict private
FConnector: Boolean;
public
procedure Recharge;
procedure UseLightning;
end;
type
TAndroid = class
strict private
FConnector: Boolean;
public
procedure Recharge;
procedure UseMicroUSB;
end;
type
TLightningToMicroUsbAdapter = class
strict private
FLightningPhone: ILightningPhone;
public
constructor Create; reintroduce;
procedure Recharge;
procedure UseMicroUSB;
end;
procedure RechargeLightningPhone;
begin
ALightningPhone.UseLightning;
ALightningPhone.Recharge;
end;
procedure RechargeMicroUSBPhone;
begin
AMicroUSBPhone.UseMicroUSB;
AMicroUSBPhone.Recharge;
end;
procedure TEdijsForm.PatternExampleButtonClick;
var
_Android: IMicroUSBPhone;
_IPhone: ILightningPhone;
_LightningToMicroUsbAdapter: IMicroUSBPhone;
begin
_Android := TAndroid.Create;
WriteLn;
RechargeMicroUSBPhone;
_IPhone := TIPhone.Create;
WriteLn;
RechargeLightningPhone;
WriteLn;
_LightningToMicroUsbAdapter := TLightningToMicroUsbAdapter.Create;
RechargeMicroUSBPhone;
end;

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

PHP


// Adapter Pattern example
interface IFormatIPhone
interface IFormatAndroid
// Adaptee
class IPhone implements IFormatIPhone
// Adapter
class IPhoneAdapter implements IFormatAndroid
class Android implements IFormatAndroid
// client
class MicroUsbRecharger
$microUsbRecharger = new MicroUsbRecharger;
class IPhoneRecharger
$iPhoneRecharger = new IPhoneRecharger;
class AndroidRecharger
$androidRecharger = new AndroidRecharger;
// Result: #quanton81
//---Recharging iPhone with Generic Recharger---
//MicroUsb connected -> Lightning connected -$
//Recharge Started
//Recharge 20%
//Recharge 50%
//Recharge 70%
//Recharge Finished
//---iPhone Ready for use---
//
//---Recharging iPhone with iPhone Recharger---
//Lightning connected -$
//Recharge Started
//Recharge 20%
//Recharge 50%
//Recharge 70%
//Recharge Finished
//---iPhone Ready for use---
//
//---Recharging Android Phone with Generic Recharger---
//MicroUsb connected ->
//Recharge Started
//Recharge 20%
//Recharge 50%
//Recharge 70%
//Recharge Finished
//---Phone Ready for use---

Scala


implicit def adaptee2Adapter: Adapter =

Python


"""
Adapter pattern example.
"""
from abc import ABCMeta, abstractmethod
NOT_IMPLEMENTED = "You should implement this."
RECHARGE =
POWER_ADAPTERS =
CONNECTED = " connected."
CONNECT_FIRST = "Connect first."
class RechargeTemplate:
__metaclass__ = ABCMeta
@abstractmethod
def recharge:
raise NotImplementedError
class FormatIPhone:
@abstractmethod
def use_lightning:
raise NotImplementedError
class FormatAndroid:
@abstractmethod
def use_micro_usb:
raise NotImplementedError
class IPhone:
__name__ = "iPhone"
def __init__:
self.connector = False
def use_lightning:
self.connector = True
print
def recharge:
if self.connector:
for state in RECHARGE:
print
else:
print
class Android:
__name__ = "Android"
def __init__:
self.connector = False
def use_micro_usb:
self.connector = True
print
def recharge:
if self.connector:
for state in RECHARGE:
print
else:
print
class IPhoneAdapter:
def __init__:
self.mobile = mobile
def recharge:
self.mobile.recharge
def use_micro_usb:
print
self.mobile.use_lightning
class AndroidRecharger:
def __init__:
self.phone = Android
self.phone.use_micro_usb
self.phone.recharge
class IPhoneMicroUSBRecharger:
def __init__:
self.phone = IPhone
self.phone_adapter = IPhoneAdapter
self.phone_adapter.use_micro_usb
self.phone_adapter.recharge
class IPhoneRecharger:
def __init__:
self.phone = IPhone
self.phone.use_lightning
self.phone.recharge
print
AndroidRecharger
print
print
IPhoneMicroUSBRecharger
print
print
IPhoneRecharger

C#


namespace WikiDesignPatterns.Adapter