Adapter Pattern
Adapter Pattern
Adapter Pattern
co m
Adapter Pattern
Motivation
T he adapter pattern is adapting between classes and objects. Like any adapter in the real world it is used to be an interf ace, a bridge between two objects. In real world we have adapters f or power supplies, adapters f or camera memory cards, and so on. Probably everyone have seen some adapters f or memory cards. If you can not plug in the camera memory in your laptop you can use and adapter. You plug the camera memory in the adapter and the adapter in to laptop slot. T hat's it, it's really simple. What about sof tware development? It's the same. Can you imagine an situation when you have some class expecting some type of object and you have an object of f ering the same f eatures, but exposing a dif f erent interf ace? Of course, you want to use both of them so you don't to implement again one of them, and you don't want to change existing classes, so why not create an adapter...
Intent
Convert the interf ace of a class into another interf ace clients expect. Adapter lets classes work together, that could not otherwise because of incompatible interf aces.
Implementation
T he f igure below shows a UML class diagram f or the Adapter Pattern:
T he classes/objects participating in adapter pattern: Target - def ines the domain-specif ic interf ace that Client uses. Adapter - adapts the interf ace Adaptee to the Target interf ace.
Adaptee - def ines an existing interf ace that needs adapting. Client - collaborates with objects conf orming to the Target interf ace.
Class adapters can be implemented in languages supporting multiple inheritance(Java, C# or PHP does not support multiple inheritance). T hus, such adapters can not be easy implemented in Java, C# or VB.NET. Class adapter uses inheritance instead of composition. It means that instead of delegating the calls to the Adaptee, it subclasses it. In conclusion it must subclass both the Target and the Adaptee. T here are advantages and disadvantages: It adapts the specif ic Adaptee class. T he class it extends. If that one is subclassed it can not be adapted by the existing adapter. It doesn't require all the code required f or delegation, which must be written f or an Object Adapter. If the Target is represented by an interf ace instead of a class then we can talk about "class" adapters, because we can implement as many interf aces as we want.