GetWiki
Adapter pattern
ARTICLE SUBJECTS
being →
database →
ethics →
fiction →
history →
internet →
language →
linux →
logic →
method →
news →
policy →
purpose →
religion →
science →
software →
truth →
unix →
wiki →
ARTICLE TYPES
essay →
feed →
help →
system →
wiki →
ARTICLE ORIGINS
critical →
forked →
imported →
original →
Adapter pattern
please note:
- the content below is remote from Wikipedia
- it has been imported raw for GetWiki
{{Short description|Design pattern in computer programming}}{{example farm|date=January 2011}}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. 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.- the content below is remote from Wikipedia
- it has been imported raw for GetWiki
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?
- 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.
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.{| class=“wikitable“! Pattern !! Intent| Converts one interface to another so that it matches what the client is expecting |
Decorator pattern>Decorator | Dynamically adds responsibility to the interface by wrapping the original code |
Delegation pattern>Delegation | Support “composition over inheritance” |
Facade pattern>Facade | Provides a simplified interface |
Structure
UML class diagram
(File:w3sDesign Adapter Design Pattern UML.jpg|frame|none|A sample UML class diagram for the adapter design pattern.)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:- 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.File:ObjectAdapter.png|thumb|300px|center|The object adapter pattern expressed in UML ]]File:Adapter(Object) pattern in LePUS3.png|thumb|500px|center|The object adapter pattern expressed in LePUS3 ]]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.File:ClassAdapter.png|thumb|300px|center|The class adapter pattern expressed in UML.]]File:Adapter(Class) pattern in LePUS3.png|thumb|500px|center|The class adapter pattern expressed in LePUS3 ]]A further form of runtime adapter pattern
Motivation from compile time solution
It is desired for {{Java|classA}} to supply {{Java|classB}} with some data, let us suppose some {{Java|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.public String getStringData() {
return format(toString());
}
Run-time adapter solution
A solution using “adapters” proceeds as follows:{{ordered list|list-style-type=lower-roman
public String getStringData();
}public class ClassAFormat1 implements StringProvider {
private ClassA classA = null;
public ClassAFormat1(final ClassA a) {
classA = a;
}
classA = a;
}
public String getStringData() {
return format(classA.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();
}
}|Write an adapter class that returns the specific implementation of the provider:public class ClassAFormat1Adapter extends Adapter {
// Manipulate the source string into a format required
// by the object needing the source object’s data
return sourceValue.trim();
}
public Object adapt(final Object anObject) {
return new ClassAFormat1((ClassA) anObject);
}
}return new ClassAFormat1((ClassA) anObject);
}
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(
.getAdapterFromTo(ClassA.class, StringProvider.class, “format1“);
((StringProvider)
AdapterFactory.getInstance()
.getAdapterFromTo(ClassA.class, StringProvider.class, “format1“)
.adapt(classA))
.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(ClassA.class, StringProvider.class, “format1“)
.adapt(classA))
.getStringData());
AdapterFactory.getInstance()
.getAdapterFromTo(ClassA.class, StringProvider.class, “format2“);
.getAdapterFromTo(ClassA.class, StringProvider.class, “format2“);
AdapterFactory.getInstance()
.getAdapterFromTo(ClassA.class, ImageProvider.class, “format2“);
ImageProvider provider = (ImageProvider) adapter.adapt(classA);classC.setImage(provider.getImage());.getAdapterFromTo(ClassA.class, ImageProvider.class, “format2“);
Implementation of the adapter pattern
When implementing the adapter pattern, for clarity, one can apply the class name {{Java|[ClassName]To[Interface]Adapter}} to the provider implementation; for example, {{Java|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 {{Java|[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.Java
interface ILightningPhone {
void recharge();
void useLightning();
}interface IMicroUsbPhone {
void useLightning();
void recharge();
void useMicroUsb();
}class Iphone implements ILightningPhone {
void useMicroUsb();
private boolean connector;
@Override
public void useLightning() {
connector = true;
System.out.println(“Lightning connected“);
}
public void useLightning() {
connector = true;
System.out.println(“Lightning connected“);
}
@Override
public void recharge() {
if (connector) {
System.out.println(“Recharge started“);
System.out.println(“Recharge finished“);
} else {
System.out.println(“Connect Lightning first“);
}
}
}class Android implements IMicroUsbPhone {
public void recharge() {
if (connector) {
System.out.println(“Recharge started“);
System.out.println(“Recharge finished“);
} else {
System.out.println(“Connect Lightning first“);
}
}
private boolean connector;
@Override
public void useMicroUsb() {
connector = true;
System.out.println(“MicroUsb connected“);
}
public void useMicroUsb() {
connector = true;
System.out.println(“MicroUsb connected“);
}
@Override
public void recharge() {
if (connector) {
System.out.println(“Recharge started“);
System.out.println(“Recharge finished“);
} else {
System.out.println(“Connect MicroUsb first“);
}
}
}/* exposing the target interface while wrapping source object */class LightningToMicroUsbAdapter implements IMicroUsbPhone {
public void recharge() {
if (connector) {
System.out.println(“Recharge started“);
System.out.println(“Recharge finished“);
} else {
System.out.println(“Connect MicroUsb first“);
}
}
private final ILightningPhone lightningPhone;
public LightningToMicroUsbAdapter(ILightningPhone lightningPhone) {
this.lightningPhone = lightningPhone;
}
this.lightningPhone = lightningPhone;
}
@Override
public void useMicroUsb() {
System.out.println(“MicroUsb connected“);
lightningPhone.useLightning();
}
public void useMicroUsb() {
System.out.println(“MicroUsb connected“);
lightningPhone.useLightning();
}
@Override
public void recharge() {
lightningPhone.recharge();
}
}public class AdapterDemo {
public void recharge() {
lightningPhone.recharge();
}
static void rechargeMicroUsbPhone(IMicroUsbPhone phone) {
phone.useMicroUsb();
phone.recharge();
}
phone.useMicroUsb();
phone.recharge();
}
static void rechargeLightningPhone(ILightningPhone phone) {
phone.useLightning();
phone.recharge();
}
phone.useLightning();
phone.recharge();
}
public static void main(String[] args) {
Android android = new Android();
Iphone iPhone = new Iphone();
Android android = new Android();
Iphone iPhone = new Iphone();
System.out.println(“Recharging android with MicroUsb“);
rechargeMicroUsbPhone(android);
rechargeMicroUsbPhone(android);
System.out.println(“Recharging iPhone with Lightning“);
rechargeLightningPhone(iPhone);
rechargeLightningPhone(iPhone);
System.out.println(“Recharging iPhone with MicroUsb“);
rechargeMicroUsbPhone(new LightningToMicroUsbAdapter (iPhone));
}
}OutputRecharging android with MicroUsbMicroUsb connectedRecharge startedRecharge finishedRecharging iPhone with LightningLightning connectedRecharge startedRecharge finishedRecharging iPhone with MicroUsbMicroUsb connectedLightning connectedRecharge startedRecharge finishedrechargeMicroUsbPhone(new LightningToMicroUsbAdapter (iPhone));
}
Python
“”“Adapter pattern example.“”“from abc import ABCMeta, abstractmethodNOT_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):
def recharge(self):
raise NotImplementedError(NOT_IMPLEMENTED)
@abstractmethod
def use_lightning(self):
raise NotImplementedError(NOT_IMPLEMENTED)
class FormatAndroid(RechargeTemplate):
def use_lightning(self):
raise NotImplementedError(NOT_IMPLEMENTED)
@abstractmethod
def use_micro_usb(self):
raise NotImplementedError(NOT_IMPLEMENTED)
class IPhone(FormatIPhone):
def use_micro_usb(self):
raise NotImplementedError(NOT_IMPLEMENTED)
__name__ = “iPhone”
def __init__(self):
self.connector = False
self.connector = False
def use_lightning(self):
self.connector = True
print(CONNECTED.format(POWER_ADAPTERS[self.__name__]))
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):
if self.connector:
for state in RECHARGE:
print(state)
else:
print(CONNECT_FIRST.format(POWER_ADAPTERS[self.__name__]))
__name__ = “Android”
def __init__(self):
self.connector = False
self.connector = False
def use_micro_usb(self):
self.connector = True
print(CONNECTED.format(POWER_ADAPTERS[self.__name__]))
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):
if self.connector:
for state in RECHARGE:
print(state)
else:
print(CONNECT_FIRST.format(POWER_ADAPTERS[self.__name__]))
def __init__(self, mobile):
self.mobile = mobile
self.mobile = mobile
def recharge(self):
self.mobile.recharge()
self.mobile.recharge()
def use_micro_usb(self):
print(CONNECTED.format(POWER_ADAPTERS[“Android”]))
self.mobile.use_lightning()
class AndroidRecharger:
print(CONNECTED.format(POWER_ADAPTERS[“Android”]))
self.mobile.use_lightning()
def __init__(self):
self.phone = Android()
self.phone.use_micro_usb()
self.phone.recharge()
class IPhoneMicroUSBRecharger:
self.phone = Android()
self.phone.use_micro_usb()
self.phone.recharge()
def __init__(self):
self.phone = IPhone()
self.phone_adapter = IPhoneAdapter(self.phone)
self.phone_adapter.use_micro_usb()
self.phone_adapter.recharge()
class IPhoneRecharger:
self.phone = IPhone()
self.phone_adapter = IPhoneAdapter(self.phone)
self.phone_adapter.use_micro_usb()
self.phone_adapter.recharge()
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()self.phone = IPhone()
self.phone.use_lightning()
self.phone.recharge()
C#
public interface ILightningPhone{ void ConnectLightning(); void Recharge();}public interface IUsbPhone{ void ConnectUsb(); void Recharge();}public sealed class AndroidPhone : IUsbPhone{ private bool isConnected; public void ConnectUsb() { this.isConnected = true; Console.WriteLine(“Android phone connected.“); } public void Recharge() { if (this.isConnected) { Console.WriteLine(“Android phone recharging.“); } else { Console.WriteLine(“Connect the USB cable first.“); } }}public sealed class ApplePhone : ILightningPhone{ private bool isConnected; public void ConnectLightning() { this.isConnected = true; Console.WriteLine(“Apple phone connected.“); } public void Recharge() { if (this.isConnected) { Console.WriteLine(“Apple phone recharging.“); } else { Console.WriteLine(“Connect the Lightning cable first.“); } }}public sealed class LightningToUsbAdapter : IUsbPhone{ private readonly ILightningPhone lightningPhone; private bool isConnected; public LightningToUsbAdapter(ILightningPhone lightningPhone) { this.lightningPhone = lightningPhone; this.lightningPhone.ConnectLightning(); } public void ConnectUsb() { this.isConnected = true; Console.WriteLine(“Adapter cable connected.“); } public void Recharge() { if (this.isConnected) { this.lightningPhone.Recharge(); } else { Console.WriteLine(“Connect the USB cable first.“); } }}public void Main(){ ILightningPhone applePhone = new ApplePhone(); IUsbPhone adapterCable = new LightningToUsbAdapter(applePhone); adapterCable.ConnectUsb(); adapterCable.Recharge();}Output:Apple phone connected.Adapter cable connected.Apple phone recharging.See also
- Adapter Java Design Patterns - Adapter
- 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).
- Ports and adapters architecture
- Shim
- Wrapper function
- Wrapper library
References
- content above as imported from Wikipedia
- "Adapter pattern" does not exist on GetWiki (yet)
- time: 7:17am EDT - Wed, May 22 2024
- "Adapter pattern" does not exist on GetWiki (yet)
- time: 7:17am EDT - Wed, May 22 2024
[ this remote article is provided by Wikipedia ]
LATEST EDITS [ see all ]
GETWIKI 21 MAY 2024
The Illusion of Choice
Culture
Culture
GETWIKI 09 JUL 2019
Eastern Philosophy
History of Philosophy
History of Philosophy
GETWIKI 09 MAY 2016
GetMeta:About
GetWiki
GetWiki
GETWIKI 18 OCT 2015
M.R.M. Parrott
Biographies
Biographies
GETWIKI 20 AUG 2014
GetMeta:News
GetWiki
GetWiki
© 2024 M.R.M. PARROTT | ALL RIGHTS RESERVED