This articlemay containexcessive orirrelevant examples. Please helpimprove it by removingless pertinent examples andelaborating on existing ones.(January 2011) (Learn how and when to remove this message) |
Insoftware engineering, theadapter pattern is asoftware design pattern (also known aswrapper, an alternative naming shared with thedecorator pattern) that allows theinterface of an existingclass to be used as another interface.[1]: 244 It is often used to make existing classes work with others without modifying theirsource code.
An example is an adapter that converts the interface of aDocument Object Model of anXML document into a tree structure that can be displayed.
The adapter[2] design pattern is one of the twenty-three well-knownGang 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]
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:
adapter class that converts the (incompatible) interface of a class (adaptee) into another interface (target) clients require.adapter to work with (reuse) classes that do not have the required interface.The key idea in this pattern is to work through a separateadapter that adapts the interface of an (already existing) class without changing it.
Clients don't know whether they work with atarget class directly or through anadapter with a class that does not have thetarget interface.
See also the UML class diagram below.
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.
An adapter can be used when the wrapper must respect a particular interface and must supportpolymorphic behavior. Alternatively, adecorator pattern makes it possible to add or alter behavior of an interface at run-time, and afacade pattern is used when an easier or simpler interface to an underlying object is desired.[1]: 243, 252, 258, 260
| 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 |

In the aboveUMLclass diagram, theclient class that requires atarget interface cannot reuse theadaptee class directly because its interface doesn't conform to thetarget interface.Instead, theclient works through anadapter class that implements thetarget interface in terms ofadaptee:
object adapter way implements thetarget interface by delegating to anadaptee object at run-time (adaptee.specificOperation()).class adapter way implements thetarget interface by inheriting from anadaptee class at compile-time (specificOperation()).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 wrappedobject.


This adapter pattern uses multiplepolymorphic 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 pureinterface class, especially inlanguages such asJava (before JDK 1.8) that do not supportmultiple inheritance of classes.[1]: 244


It is desired forclassA to supplyclassB with some data, let us suppose someString 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:
publicclassFormat1ClassAextendsClassA{@OverridepublicStringgetStringData(){returnformat(toString());}}
and perhaps create the correctly "formatting" object at runtime by means of thefactory pattern.
A solution using "adapters" proceeds as follows:
ClassA in this example, and outputs the data formatted as appropriate:interfaceStringProvider{publicStringgetStringData();}publicclassClassAFormat1implementsStringProvider{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 datareturnsourceValue.trim();}}
publicclassClassAFormat1AdapterextendsAdapter{publicObjectadapt(finalObjectanObject){returnnewClassAFormat1((ClassA)anObject);}}
adapter with a global registry, so that theadapter can be looked up at runtime:AdapterFactory.getInstance().registerAdapter(ClassA.class,ClassAFormat1Adapter.class,"format1");
ClassA toClassB, 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());
Adapteradapter=AdapterFactory.getInstance().getAdapterFromTo(ClassA.class,StringProvider.class,"format2");
ClassA as, say, image data inClassC:Adapteradapter=AdapterFactory.getInstance().getAdapterFromTo(ClassA.class,ImageProvider.class,"format2");ImageProviderprovider=(ImageProvider)adapter.adapt(classA);classC.setImage(provider.getImage());
ClassB andClassC intoClassA 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.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.
packageorg.wikipedia.examples;interfaceILightningPhone{voidrecharge();voiduseLightning();}interfaceIMicroUsbPhone{voidrecharge();voiduseMicroUsb();}classIphoneimplementsILightningPhone{privatebooleanconnector;@OverridepublicvoiduseLightning(){connector=true;System.out.println("Lightning connected");}@Overridepublicvoidrecharge(){if(connector){System.out.println("Recharge started");System.out.println("Recharge finished");}else{System.out.println("Connect Lightning first");}}}classAndroidimplementsIMicroUsbPhone{privatebooleanconnector;@OverridepublicvoiduseMicroUsb(){connector=true;System.out.println("MicroUsb connected");}@Overridepublicvoidrecharge(){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 */classLightningToMicroUsbAdapterimplementsIMicroUsbPhone{privatefinalILightningPhonelightningPhone;publicLightningToMicroUsbAdapter(ILightningPhonelightningPhone){this.lightningPhone=lightningPhone;}@OverridepublicvoiduseMicroUsb(){System.out.println("MicroUsb connected");lightningPhone.useLightning();}@Overridepublicvoidrecharge(){lightningPhone.recharge();}}publicclassAdapterDemo{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 MicroUsbMicroUsb connectedRecharge startedRecharge finishedRecharging iPhone with LightningLightning connectedRecharge startedRecharge finishedRecharging iPhone with MicroUsbMicroUsb connectedLightning connectedRecharge startedRecharge finished
"""Adapter pattern example."""fromabcimportABCMeta,abstractmethodfromtypingimportNoReturnRECHARGE: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):@abstractmethoddefrecharge(self)->NoReturn:raiseNotImplementedError("You should implement this.")classFormatIPhone(RechargeTemplate):@abstractmethoddefuse_lightning(self)->NoReturn:raiseNotImplementedError("You should implement this.")classFormatAndroid(RechargeTemplate):@abstractmethoddefuse_micro_usb(self)->NoReturn:raiseNotImplementedError("You should implement this.")classIPhone(FormatIPhone):__name__:str="iPhone"def__init__(self):self.connector:bool=Falsedefuse_lightning(self)->None:self.connector=Trueprint(CONNECTED_MSG.format(POWER_ADAPTERS[self.__name__]))defrecharge(self)->None:ifself.connector:forstateinRECHARGE:print(state)else:print(CONNECT_FIRST_MSG.format(POWER_ADAPTERS[self.__name__]))classAndroid(FormatAndroid):__name__:str="Android"def__init__(self)->None:self.connector:bool=Falsedefuse_micro_usb(self)->None:self.connector=Trueprint(CONNECTED_MSG.format(POWER_ADAPTERS[self.__name__]))defrecharge(self)->None:ifself.connector:forstateinRECHARGE:print(state)else:print(CONNECT_FIRST_MSG.format(POWER_ADAPTERS[self.__name__]))classIPhoneAdapter(FormatAndroid):def__init__(self,mobile:FormatAndroid)->None:self.mobile:FormatAndroid=mobiledefrecharge(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()
namespaceWikipedia.Examples;usingSystem;interfaceILightningPhone{voidConnectLightning();voidRecharge();}interfaceIUsbPhone{voidConnectUsb();voidRecharge();}sealedclassAndroidPhone: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.");}}}sealedclassApplePhone:ILightningPhone{privateboolisConnected;publicvoidConnectLightning(){this.isConnected=true;Console.WriteLine("Apple phone connected.");}publicvoidRecharge(){if(this.isConnected){Console.WriteLine("Apple phone recharging.");}else{Console.WriteLine("Connect the Lightning cable first.");}}}sealedclassLightningToUsbAdapter:IUsbPhone{privatereadonlyILightningPhonelightningPhone;privateboolisConnected;publicLightningToUsbAdapter(ILightningPhonelightningPhone){this.lightningPhone=lightningPhone;}publicvoidConnectUsb(){this.lightningPhone.ConnectLightning();}publicvoidRecharge(){this.lightningPhone.Recharge();}}publicclassAdapterDemo{staticvoidMain(string[]args){ILightningPhoneapplePhone=newApplePhone();IUsbPhoneadapterCable=newLightningToUsbAdapter(applePhone);adapterCable.ConnectUsb();adapterCable.Recharge();}}
Output:
Apple phone connected.Apple phone recharging.