Jump to content
Wikipedia The Free Encyclopedia

Adapter pattern

From Wikipedia, the free encyclopedia
Design pattern in computer programming
This article may contain excessive or irrelevant examples. Please help improve it by removing less pertinent examples and elaborating on existing ones. (January 2011) (Learn how and when to remove this message)

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.

Overview

[edit ]

The adapter[2] 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:[3]

  • 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 not be reused only because its interface does not 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

[edit ]

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

[edit ]

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.[4]

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

[edit ]

UML class diagram

[edit ]
A sample UML class diagram for the adapter design pattern.[5]

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

[edit ]

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.

The object adapter pattern expressed in UML
The object adapter pattern expressed in LePUS3

Class adapter pattern

[edit ]

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]

The class adapter pattern expressed in UML.
The class adapter pattern expressed in LePUS3

A further form of runtime adapter pattern

[edit ]

Motivation from compile time solution

[edit ]

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:

publicclass Format1ClassAextendsClassA{
@Override
publicStringgetStringData(){
returnformat(toString());
}
}

and perhaps create the correctly "formatting" object at runtime by means of the factory pattern.

Run-time adapter solution

[edit ]

A solution using "adapters" proceeds as follows:

  1. 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:
    publicinterface StringProvider{
    publicStringgetStringData();
    }
    publicclass ClassAFormat1implementsStringProvider{
    privateClassAclassA=null;
    publicClassAFormat1(finalClassAa){
    classA=a;
    }
    publicStringgetStringData(){
    returnformat(classA.getStringData());
    }
    privateStringformat(finalStringsourceValue){
    // Manipulate the source string into a format required 
    // by the object needing the source object's data
    returnsourceValue.trim();
    }
    }
    
  2. Write an adapter class that returns the specific implementation of the provider:
    publicclass ClassAFormat1AdapterextendsAdapter{
    publicObjectadapt(finalObjectanObject){
    returnnewClassAFormat1((ClassA)anObject);
    }
    }
    
  3. 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");
    
  4. In code, when wishing to transfer data from ClassA to ClassB, write:
    Adapteradapter=AdapterFactory.getInstance()
    .getAdapterFromTo(ClassA.class,StringProvider.class,"format1");
    StringProviderprovider=(StringProvider)adapter.adapt(classA);
    Stringstring=provider.getStringData();
    classB.setStringData(string);
    

    or more concisely:

    classB.setStringData(((StringProvider)AdapterFactory.getInstance()
    .getAdapterFromTo(ClassA.class,StringProvider.class,"format1")
    .adapt(classA))
    .getStringData()
    );
    
  5. 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:
    Adapteradapter=AdapterFactory.getInstance()
    .getAdapterFromTo(ClassA.class,StringProvider.class,"format2");
    
  6. And if it is desired to output the data from ClassA as, say, image data in ClassC:
    Adapteradapter=AdapterFactory.getInstance()
    .getAdapterFromTo(ClassA.class,ImageProvider.class,"format2");
    ImageProviderprovider=(ImageProvider)adapter.adapt(classA);
    classC.setImage(provider.getImage());
    
  7. 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

[edit ]

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.

Java

[edit ]
interface ILightningPhone{
voidrecharge();
voiduseLightning();
}
interface IMicroUsbPhone{
voidrecharge();
voiduseMicroUsb();
}
class IphoneimplementsILightningPhone{
privatebooleanconnector;
@Override
publicvoiduseLightning(){
connector=true;
System.out.println("Lightning connected");
}
@Override
publicvoidrecharge(){
if(connector){
System.out.println("Recharge started");
System.out.println("Recharge finished");
}else{
System.out.println("Connect Lightning first");
}
}
}
class AndroidimplementsIMicroUsbPhone{
privatebooleanconnector;
@Override
publicvoiduseMicroUsb(){
connector=true;
System.out.println("MicroUsb connected");
}
@Override
publicvoidrecharge(){
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 LightningToMicroUsbAdapterimplementsIMicroUsbPhone{
privatefinalILightningPhonelightningPhone;
publicLightningToMicroUsbAdapter(ILightningPhonelightningPhone){
this.lightningPhone=lightningPhone;
}
@Override
publicvoiduseMicroUsb(){
System.out.println("MicroUsb connected");
lightningPhone.useLightning();
}
@Override
publicvoidrecharge(){
lightningPhone.recharge();
}
}
publicclass AdapterDemo{
staticvoidrechargeMicroUsbPhone(IMicroUsbPhonephone){
phone.useMicroUsb();
phone.recharge();
}
staticvoidrechargeLightningPhone(ILightningPhonephone){
phone.useLightning();
phone.recharge();
}
publicstaticvoidmain(String[]args){
Androidandroid=newAndroid();
IphoneiPhone=newIphone();
System.out.println("Recharging android with MicroUsb");
rechargeMicroUsbPhone(android);
System.out.println("Recharging iPhone with Lightning");
rechargeLightningPhone(iPhone);
System.out.println("Recharging iPhone with MicroUsb");
rechargeMicroUsbPhone(newLightningToMicroUsbAdapter(iPhone));
}
}

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

[edit ]
"""
Adapter pattern example.
"""
fromabcimport ABCMeta, abstractmethod
fromtypingimport Dict, List, NoReturn
RECHARGE: List[str] = ["Recharge started.", "Recharge finished."]
POWER_ADAPTERS: Dict[str, str] = {"Android": "MicroUSB", "iPhone": "Lightning"}
CONNECTED_MSG: str = "{} connected."
CONNECT_FIRST_MSG: str = "Connect {} first."
classRechargeTemplate(metaclass = ABCMeta):
 @abstractmethod
 defrecharge(self) -> NoReturn:
 raise NotImplementedError("You should implement this.")
classFormatIPhone(RechargeTemplate):
 @abstractmethod
 defuse_lightning(self) -> NoReturn:
 raise NotImplementedError("You should implement this.")
classFormatAndroid(RechargeTemplate):
 @abstractmethod
 defuse_micro_usb(self) -> NoReturn:
 raise NotImplementedError("You should implement this.")
classIPhone(FormatIPhone):
 __name__: str = "iPhone"
 def__init__(self):
 self.connector: bool = False
 defuse_lightning(self) -> None:
 self.connector = True
 print(CONNECTED_MSG.format(POWER_ADAPTERS[self.__name__]))
 defrecharge(self) -> None:
 if self.connector:
 for state in RECHARGE:
 print(state)
 else:
 print(CONNECT_FIRST_MSG.format(POWER_ADAPTERS[self.__name__]))
classAndroid(FormatAndroid):
 __name__: str = "Android"
 def__init__(self) -> None:
 self.connector: bool = False
 defuse_micro_usb(self) -> None:
 self.connector = True
 print(CONNECTED_MSG.format(POWER_ADAPTERS[self.__name__]))
 defrecharge(self) -> None:
 if self.connector:
 for state in RECHARGE:
 print(state)
 else:
 print(CONNECT_FIRST_MSG.format(POWER_ADAPTERS[self.__name__]))
classIPhoneAdapter(FormatAndroid):
 def__init__(self, mobile: FormatAndroid) -> None:
 self.mobile: FormatAndroid = mobile
 defrecharge(self) -> None:
 self.mobile.recharge()
 defuse_micro_usb(self) -> None:
 print(CONNECTED_MSG.format(POWER_ADAPTERS["Android"]))
 self.mobile.use_lightning()
classAndroidRecharger:
 def__init__(self) -> None:
 self.phone: Android = Android()
 self.phone.use_micro_usb()
 self.phone.recharge()
classIPhoneMicroUSBRecharger:
 def__init__(self) -> None:
 self.phone: IPhone = IPhone()
 self.phone_adapter: IPhoneAdapter = IPhoneAdapter(self.phone)
 self.phone_adapter.use_micro_usb()
 self.phone_adapter.recharge()
classIPhoneRecharger:
 def__init__(self) -> None:
 self.phone: IPhone = 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#

[edit ]
publicinterfaceILightningPhone
{
voidConnectLightning();
voidRecharge();
}
publicinterfaceIUsbPhone
{
voidConnectUsb();
voidRecharge();
}
publicsealedclassAndroidPhone:IUsbPhone
{
privateboolisConnected;
publicvoidConnectUsb()
{
this.isConnected=true;
Console.WriteLine("Android phone connected.");
}
publicvoidRecharge()
{
if(this.isConnected)
{
Console.WriteLine("Android phone recharging.");
}
else
{
Console.WriteLine("Connect the USB cable first.");
}
}
}
publicsealedclassApplePhone:ILightningPhone
{
privateboolisConnected;
publicvoidConnectLightning()
{
this.isConnected=true;
Console.WriteLine("Apple phone connected.");
}
publicvoidRecharge()
{
if(this.isConnected)
{
Console.WriteLine("Apple phone recharging.");
}
else
{
Console.WrizteLine("Connect the Lightning cable first.");
}
}
}
publicsealedclassLightningToUsbAdapter:IUsbPhone
{
privatereadonlyILightningPhonelightningPhone;
privateboolisConnected;
publicLightningToUsbAdapter(ILightningPhonelightningPhone)
{
this.lightningPhone=lightningPhone;
}
publicvoidConnectUsb()
{
this.lightningPhone.ConnectLightning();
}
publicvoidRecharge()
{
this.lightningPhone.Recharge();
}
}
publicvoidMain()
{
ILightningPhoneapplePhone=newApplePhone();
IUsbPhoneadapterCable=newLightningToUsbAdapter(applePhone);
adapterCable.ConnectUsb();
adapterCable.Recharge();
}

Output:

Apple phone connected.
Apple phone recharging.

See also

[edit ]

References

[edit ]
  1. ^ a b Freeman, Eric; Freeman, Elisabeth; Sierra, Kathy; Bates, Bert (2004). Head First Design Patterns. O'Reilly Media. p. 244. ISBN 978-0-596-00712-6. OCLC 809772256. Archived from the original (paperback) on 2013年05月04日. Retrieved 2013年04月30日.
  2. ^ Gamma, Erich; Helm, Richard; Johnson, Ralph; Vlissides, John (1994). Design Patterns: Elements of Reusable Object-Oriented Software . Addison Wesley. pp. 139ff. ISBN 0-201-63361-2.
  3. ^ "The Adapter design pattern - Problem, Solution, and Applicability". w3sDesign.com. Archived from the original on 2017年08月28日. Retrieved 2017年08月12日.
  4. ^ Freeman, Eric; Freeman, Elisabeth; Sierra, Kathy; Bates, Bert (2004). Hendrickson, Mike; Loukides, Mike (eds.). Head First Design Patterns (paperback). Vol. 1. O'Reilly Media. pp. 243, 252, 258, 260. ISBN 978-0-596-00712-6 . Retrieved 2012年07月02日.
  5. ^ "The Adapter design pattern - Structure and Collaboration". w3sDesign.com. Archived from the original on 2017年08月28日. Retrieved 2017年08月12日.
Wikimedia Commons has media related to Adapter pattern .
Gang of Four
patterns
Creational
Structural
Behavioral
Concurrency
patterns
Architectural
patterns
Other
patterns
Books
People
Communities
See also

AltStyle によって変換されたページ (->オリジナル) /