Tuesday, June 29, 2010

Adapter Pattern

In computer programming, adapter/wrapper pattern is a design pattern that translates one interface or class into compatible interface. This pattern enables incompatible classes to work together by providing compatible interface of original class to its client, i.e. this pattern translate calls made by client to interface into a calls to the original class/interface. The adapter class is also responsible for converting data responded by original class/interface to be converted into form easily understandable by client. For example if interface evaluates a call into a Boolean which client expected it to be integer 1/0 then it is responsibility of adapter class to evaluate a call response into format that is understandable by client class.

There are two types of adapter pattern:

  • Object Adapter pattern: In this pattern, adapter class contain object of class it wraps, i.e., adapter class redirect calls from client class to the wrapped class.
    It uses Composition method for adapting Adaptee and this adaption can be extended to sub-class of Adaptee
    Object Adapter class delegates execution of behaviour to Adaptee class
  • Class Adapter pattern: In this pattern, multiple inheritance is used to address the issue. Interface of existing implementation as well as interface of expected implementation is inherited by the adapter class so that it behaves as an expected implementation. This type of implementation is used in situation where existing implementation provide some or all of the services expected but does not use expected interfaces.
    It uses Inheritance method for adapting Adaptee hence Adapter class doesn't requires to reimplement entire Adaptee class, but only needs to override the behaviour of Adaptee class that varies.

Flow of control in Adapter pattern

  • Client makes an request to Adapter class by invoking its method using Target interface.
  • Adapter object translate this request into single or series of method call to Adaptee object.
  • Client receive back the response, without knowing that translation is done by Adapter.

Object Adapter Pattern

Object Adapter Pattern class diagram

Class Adapter Pattern

Class Adapter Pattern class diagram

Note: Adapter pattern is never implemented when designing a new system but with the changing requirements we have deferring interfaces then adapter comes into picture.

No comments:

Post a Comment