Adapter pattern

Last updated

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.

Contents

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

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:

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

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

PatternIntent
Adapter or wrapperConverts 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

UML class diagram

A sample UML class diagram for the adapter design pattern. W3sDesign Adapter Design Pattern UML.jpg
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:

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.

The object adapter pattern expressed in UML ObjectAdapter.png
The object adapter pattern expressed in UML
The object adapter pattern expressed in LePUS3 Adapter(Object) pattern in LePUS3.png
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. [1]

The class adapter pattern expressed in UML. ClassAdapter.png
The class adapter pattern expressed in UML.
The class adapter pattern expressed in LePUS3 Adapter(Class) pattern in LePUS3.png
The class adapter pattern expressed in LePUS3

A further form of runtime adapter pattern

Motivation from compile time solution

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:

publicclassFormat1ClassAextendsClassA{@OverridepublicStringgetStringData(){returnformat(toString());}}

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:

  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:
    publicinterfaceStringProvider{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();}}
  2. Write an adapter class that returns the specific implementation of the provider:
    publicclassClassAFormat1AdapterextendsAdapter{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

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

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 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

"""Adapter pattern example."""fromabcimportABCMeta,abstractmethodNOT_IMPLEMENTED="You should implement this."RECHARGE=["Recharge started.","Recharge finished."]POWER_ADAPTERS={"Android":"MicroUSB","iPhone":"Lightning"}CONNECTED="{} connected."CONNECT_FIRST="Connect {} first."classRechargeTemplate(metaclass=ABCMeta):@abstractmethoddefrecharge(self):raiseNotImplementedError(NOT_IMPLEMENTED)classFormatIPhone(RechargeTemplate):@abstractmethoddefuse_lightning(self):raiseNotImplementedError(NOT_IMPLEMENTED)classFormatAndroid(RechargeTemplate):@abstractmethoddefuse_micro_usb(self):raiseNotImplementedError(NOT_IMPLEMENTED)classIPhone(FormatIPhone):__name__="iPhone"def__init__(self):self.connector=Falsedefuse_lightning(self):self.connector=Trueprint(CONNECTED.format(POWER_ADAPTERS[self.__name__]))defrecharge(self):ifself.connector:forstateinRECHARGE:print(state)else:print(CONNECT_FIRST.format(POWER_ADAPTERS[self.__name__]))classAndroid(FormatAndroid):__name__="Android"def__init__(self):self.connector=Falsedefuse_micro_usb(self):self.connector=Trueprint(CONNECTED.format(POWER_ADAPTERS[self.__name__]))defrecharge(self):ifself.connector:forstateinRECHARGE:print(state)else:print(CONNECT_FIRST.format(POWER_ADAPTERS[self.__name__]))classIPhoneAdapter(FormatAndroid):def__init__(self,mobile):self.mobile=mobiledefrecharge(self):self.mobile.recharge()defuse_micro_usb(self):print(CONNECTED.format(POWER_ADAPTERS["Android"]))self.mobile.use_lightning()classAndroidRecharger:def__init__(self):self.phone=Android()self.phone.use_micro_usb()self.phone.recharge()classIPhoneMicroUSBRecharger:def__init__(self):self.phone=IPhone()self.phone_adapter=IPhoneAdapter(self.phone)self.phone_adapter.use_micro_usb()self.phone_adapter.recharge()classIPhoneRecharger: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()

C#

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.WriteLine("Connect the Lightning cable first.");}}}publicsealedclassLightningToUsbAdapter:IUsbPhone{privatereadonlyILightningPhonelightningPhone;privateboolisConnected;publicLightningToUsbAdapter(ILightningPhonelightningPhone){this.lightningPhone=lightningPhone;this.lightningPhone.ConnectLightning();}publicvoidConnectUsb(){this.isConnected=true;Console.WriteLine("Adapter cable connected.");}publicvoidRecharge(){if(this.isConnected){this.lightningPhone.Recharge();}else{Console.WriteLine("Connect the USB cable first.");}}}publicvoidMain(){ILightningPhoneapplePhone=newApplePhone();IUsbPhoneadapterCable=newLightningToUsbAdapter(applePhone);adapterCable.ConnectUsb();adapterCable.Recharge();}

Output:

Apple phone connected.Adapter cable connected.Apple phone recharging.

See also

Related Research Articles

<span class="mw-page-title-main">USB</span> Standard for computer data connections

Universal Serial Bus (USB) is an industry standard that allows data exchange and delivery of power between many various types of electronics. It specifies its architecture, in particular its physical interface, and communication protocols for data transfer and power delivery to and from hosts, such as personal computers, to and from peripheral devices, e.g. displays, keyboards, and mass storage devices, and to and from intermediate hubs, which multiply the number of a host's ports.

A visitor pattern is a software design pattern that separates the algorithm from the object structure. Because of this separation new operations can be added to existing object structures without modifying the structures. It is one way to follow the open/closed principle in object-oriented programming and software engineering.

The bridge pattern is a design pattern used in software engineering that is meant to "decouple an abstraction from its implementation so that the two can vary independently", introduced by the Gang of Four. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.

In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. It is a kind of lazy evaluation that refers specifically to the instantiation of objects or other resources.

The memento pattern is a software design pattern that exposes the private internal state of an object. One example of how this can be used is to restore an object to its previous state, another is versioning, another is custom serialization.

In object oriented programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.

In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other instances of the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern as well as to the Open-Closed Principle, by allowing the functionality of a class to be extended without being modified. Decorator use can be more efficient than subclassing, because an object's behavior can be augmented without defining an entirely new object.

In software engineering, the mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program's running behavior.

In software design and engineering, the observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

In computer programming, the strategy pattern is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.

<span class="mw-page-title-main">Method overriding</span> Language feature in object-oriented programming

Method overriding, in object-oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes. In addition to providing data-driven algorithm-determined parameters across virtual network interfaces, it also allows for a specific type of polymorphism (subtyping). The implementation in the subclass overrides (replaces) the implementation in the superclass by providing a method that has same name, same parameters or signature, and same return type as the method in the parent class. The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed. This helps in preventing problems associated with differential relay analytics which would otherwise rely on a framework in which method overriding might be obviated. Some languages allow a programmer to prevent a method from being overridden.

<span class="mw-page-title-main">USB On-The-Go</span> Specification for USB devices

USB On-The-Go is a specification first used in late 2001 that allows USB devices, such as tablets or smartphones, to also act as a host, allowing other USB devices, such as USB flash drives, digital cameras, mouse or keyboards, to be attached to them. Use of USB OTG allows devices to switch back and forth between the roles of host and device. For example, a smartphone may read from removable media as the host device, but present itself as a USB Mass Storage Device when connected to a host computer.

In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL). The term was coined in 2005 by Eric Evans and Martin Fowler.

Mobile High-Definition Link (MHL) is an industry standard for a mobile audio/video interface that allows the connection of smartphones, tablets, and other portable consumer electronics devices to high-definition televisions (HDTVs), audio receivers, and projectors. The standard was designed to share existing mobile device connectors, such as Micro-USB, and avoid the need to add video connectors on devices with limited space for them.

<span class="mw-page-title-main">Universal charger</span>

Universal charger or common charger refers to various projects to standardize the connectors of power supplies, particularly for battery-powered devices.

The Archetype pattern separates the logic from implementation; the separation is accomplished by there being two abstract classes, a decorator and a delegate. The Factory handles the mapping of decorator and delegate classes and returns the pair associated with a parameter or parameters passed. The interface is the contract between a decorator, a delegate and the calling class creating an Inversion of Responsibility. This example use two branches however you can have 'N' branches as required. The pattern means that one branch from the interface does not have to worry about how another branch operators as long it implements the interface.

In software engineering, the module pattern is a design pattern used to implement the concept of software modules, defined by modular programming, in a programming language with incomplete direct support for the concept.

<span class="mw-page-title-main">USB-C</span> 24-pin USB connector system

USB-C, or USB Type-C, is a 24-pin connector that supersedes previous USB connectors and can carry audio, video and other data, e.g., to drive multiple displays, to store a backup to an external drive. It can also provide and receive power, such as powering a laptop or a mobile phone. It is applied not only by USB technology, but also by other protocols, including Thunderbolt, PCIe, HDMI, DisplayPort, and others. It is extensible to support future standards.

In object-oriented programming, forwarding means that using a member of an object results in actually using the corresponding member of a different object: the use is forwarded to another object. Forwarding is used in a number of design patterns, where some members are forwarded to another object, while others are handled by the directly used object. The forwarding object is frequently called a wrapper object, and explicit forwarding members are called wrapper functions.

The initial versions of the USB standard specified connectors that were easy to use and that would have acceptable life spans; revisions of the standard added smaller connectors useful for compact portable devices. Higher-speed development of the USB standard gave rise to another family of connectors to permit additional data paths. All versions of USB specify cable properties; version 3.x cables include additional data paths. The USB standard included power supply to peripheral devices; modern versions of the standard extend the power delivery limits for battery charging and devices requiring up to 240 watts. USB has been selected as the standard charging format for many mobile phones, reducing the proliferation of proprietary chargers.

References

  1. 1 2 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.