Adapter pattern
In software engineering, the adapter pattern is a software design pattern (also known as Wrapper, an alternative naming shared with the Decorator pattern) that allows the interface of an existing class to be used as another interface.[1] 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.
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.[2]
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
There are two adapter patterns:[1]
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 (before jdk 1.8) that do not support multiple inheritance of classes.[1]
A further form of runtime Adapter pattern
There is a further form of runtime adapter pattern as follows:
It is desired for classA
to supply classB
with some data, let us suppose some String
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 {
@Override
public String getStringData() {
return format(toString());
}
}
and perhaps create the correctly "formatting" object at runtime by means of the Factory pattern.
A solution using "adapters" proceeds as follows:
(i) Define an intermediary "Provider" interface, and write an implementation of that Provider interface that wraps the source of the data, ClassA
in this example, and outputs the data formatted as appropriate:
public interface StringProvider {
public String getStringData();
}
public class ClassAFormat1 implements StringProvider {
private ClassA classA = null;
public ClassAFormat1(final ClassA a) {
classA = a;
}
public String getStringData() {
return format(classA.getStringData());
}
private String format(final String sourceValue) {
// Manipulate the source string into a format required
// by the object needing the source object's data
return sourceValue.trim();
}
}
(ii) Write an Adapter class that returns the specific implementation of the Provider:
public class ClassAFormat1Adapter extends Adapter {
public Object adapt(final Object anObject) {
return new ClassAFormat1((ClassA) anObject);
}
}
(iii) Register the Adapter
with a global registry, so that the Adapter
can be looked up at runtime:
AdapterFactory.getInstance().registerAdapter(ClassA.class, ClassAFormat1Adapter.class, "format1");
(iv) In code, when wishing to transfer data from ClassA
to ClassB
, write:
Adapter adapter =
AdapterFactory.getInstance()
.getAdapterFromTo(ClassA.class, StringProvider.class, "format1");
StringProvider provider = (StringProvider) adapter.adapt(classA);
String string = provider.getStringData();
classB.setStringData(string);
or more concisely:
classB.setStringData(
((StringProvider)
AdapterFactory.getInstance()
.getAdapterFromTo(ClassA.class, StringProvider.class, "format1")
.adapt(classA))
.getStringData());
(v) 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(ClassA.class, StringProvider.class, "format2");
(vi) And if it is desired to output the data from ClassA
as, say, image data in Class C
:
Adapter adapter =
AdapterFactory.getInstance()
.getAdapterFromTo(ClassA.class, ImageProvider.class, "format2");
ImageProvider provider = (ImageProvider) adapter.adapt(classA);
classC.setImage(provider.getImage());
(vii) In this way, the use of adapters and providers allows multiple "views" by ClassB
and ClassC
into ClassA
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 [ClassName]To[Interface]Adapter
to the provider implementation, for example DAOToProviderAdapter
. It should have a constructor method with an adaptee class variable as a parameter. This parameter will be passed to an instance member of [ClassName]To[Interface]Adapter
. 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
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"
end
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(@mobile)
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)
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
public class AdapteeToClientAdapter implements Adapter {
private final Adaptee instance;
public AdapteeToClientAdapter(final Adaptee instance) {
this.instance = instance;
}
@Override
public void clientMethod() {
// call Adaptee's method(s) to implement Client's clientMethod
}
}
PHP
// Adapter Pattern example
interface IFormatIPhone
{
public function recharge();
public function useLightning();
}
interface IFormatAndroid
{
public function recharge();
public function useMicroUsb();
}
// Adaptee
class IPhone implements IFormatIPhone
{
private $connectorOk = FALSE;
public function useLightning()
{
$this->connectorOk = TRUE;
echo "Lightning connected -$\n";
}
public function recharge()
{
if($this->connectorOk)
{
echo "Recharge Started\n";
echo "Recharge 20%\n";
echo "Recharge 50%\n";
echo "Recharge 70%\n";
echo "Recharge Finished\n";
}
else
{
echo "Connect Lightning first\n";
}
}
}
// Adapter
class IPhoneAdapter implements IFormatAndroid
{
private $mobile;
public function __construct(IFormatIPhone $mobile)
{
$this->mobile = $mobile;
}
public function recharge()
{
$this->mobile->recharge();
}
public function useMicroUsb()
{
echo "MicroUsb connected -> ";
$this->mobile->useLightning();
}
}
class Android implements IFormatAndroid
{
private $connectorOk = FALSE;
public function useMicroUsb()
{
$this->connectorOk = TRUE;
echo "MicroUsb connected ->\n";
}
public function recharge()
{
if($this->connectorOk)
{
echo "Recharge Started\n";
echo "Recharge 20%\n";
echo "Recharge 50%\n";
echo "Recharge 70%\n";
echo "Recharge Finished\n";
}
else
{
echo "Connect MicroUsb first\n";
}
}
}
// client
class MicroUsbRecharger
{
private $phone;
private $phoneAdapter;
public function __construct()
{
echo "---Recharging iPhone with Generic Recharger---\n";
$this->phone = new IPhone();
$this->phoneAdapter = new IPhoneAdapter($this->phone);
$this->phoneAdapter->useMicroUsb();
$this->phoneAdapter->recharge();
echo "---iPhone Ready for use---\n\n";
}
}
$microUsbRecharger = new MicroUsbRecharger();
class IPhoneRecharger
{
private $phone;
public function __construct()
{
echo "---Recharging iPhone with iPhone Recharger---\n";
$this->phone = new IPhone();
$this->phone->useLightning();
$this->phone->recharge();
echo "---iPhone Ready for use---\n\n";
}
}
$iPhoneRecharger = new IPhoneRecharger();
class AndroidRecharger
{
private $phone;
public function __construct()
{
echo "---Recharging Android Phone with Generic Recharger---\n";
$this->phone = new Android();
$this->phone->useMicroUsb();
$this->phone->recharge();
echo "---Phone Ready for use---\n\n";
}
}
$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(adaptee: Adaptee): Adapter = {
new Adapter {
override def clientMethod: Unit = {
// call Adaptee's method(s) to implement Client's clientMethod */
}
}
}
Python
"""
Adapter pattern example.
"""
from abc import ABCMeta, abstractmethod
NOT_IMPLEMENTED = "You should implement this."
RECHARGE = ["Recharge started.", "Recharge finished."]
POWER_ADAPTERS = {"Android": "MicroUSB", "iPhone": "Lightning"}
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[self.__name__]))
def recharge(self):
if self.connector:
for state in RECHARGE:
print(state)
else:
print(CONNECT_FIRST.format(POWER_ADAPTERS[self.__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[self.__name__]))
def recharge(self):
if self.connector:
for state in RECHARGE:
print(state)
else:
print(CONNECT_FIRST.format(POWER_ADAPTERS[self.__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(object):
def __init__(self):
self.phone = Android()
self.phone.use_micro_usb()
self.phone.recharge()
class IPhoneMicroUSBRecharger(object):
def __init__(self):
self.phone = IPhone()
self.phone_adapter = IPhoneAdapter(self.phone)
self.phone_adapter.use_micro_usb()
self.phone_adapter.recharge()
class IPhoneRecharger(object):
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()
See also
- Delegation, strongly relevant to the object adapter pattern.
- Dependency inversion principle, 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).
- Shim
- Wrapper function
- Wrapper library
References
- 1 2 3 Freeman, Eric; Freeman, Elisabeth; Kathy, Sierra; Bates, Bert (2004). "Head First Design Patterns" (paperback). O'Reilly Media: 244. ISBN 978-0-596-00712-6. OCLC 809772256. Retrieved April 30, 2013.
- ↑ Freeman, Eric; Freeman, Elisabeth; Sierra, Kathy; Bates, Bert (2004). Hendrickson, Mike; Loukides, Mike, eds. "Head First Design Patterns" (paperback). 1. O'Reilly: 243, 252, 258, 260. ISBN 978-0-596-00712-6. Retrieved 2012-07-02.
Wikimedia Commons has media related to Adapter pattern. |
The Wikibook Computer Science Design Patterns has a page on the topic of: Adapter implementations in various languages |