Saturday, 24 March 2007

Adapter Pattern (Week - 5)

Today's lecture was about the first structural pattern called Adapter pattern. The lecture was divided into two sessions; first session was about introduction to Adapter pattern and second session was about some practical examples of Adapter pattern.

From my understanding of the pattern I think; the basic purpose of adapter pattern is to make two incompatible interfaces compatible. It makes different classes to work together even if they are not compatible with each other. This pattern is also known as wrapper as it wraps itself around the class interface in order to convert into another interface which client expects. The adapter is also responsible for handling any logic necessary to transform data into a form that is useful for the consumer. For instance, if multiple Boolean values are stored as a single integer but your consumer requires a 'true'/'false', the adapter would be responsible for extracting the appropriate values from the integer value. [1]

A very good example was given by Dr. Sri; consider a laptop being bought from another country and is brought in UK, now that laptop has two pin plug and works with two pin socket. We have to use an adapter in order to make it compatible with three pin socket that are used in Britain.

This pattern is used when;

  • User wants to use existing class but the interface doesn't match user needs
  • Creating a class that communicates with unrelated classes

There are two types of this pattern; Object Adapter pattern and Class Adapter pattern

Object Adapter Pattern

In this pattern the adapter hold the instance of the class it wraps and makes call to the instance of the wrapped object.

Class Adapter Pattern

The class adapter pattern uses the concept of multiple inheritance. The adapter is created inheriting interfaces from both the interface that is expected and the interface that is pre-existing. [1]

The object adapter pattern is more often used than class adapter pattern. Class adapter pattern can not be used with Java because of the concept of multiple inheritance, that is not supported by Java.

Reference

[1] Adapter Pattern
Available from URL
http://en.wikipedia.org/wiki/Adapter_pattern

3 comments:

Hani said...

Hi abbas again,Well i am trying to gain as much as i can from you.I didnt understand Object Adapter Pattern! Could u plz briefly tell me more about it if possible with the help of some simple example..!Would be appreciated..Thnx

Bash said...

Let me make it abit more simpler, if I may. The Adapter Pattern converts the programming interface of one class in to that of another. You can use adapters, whenever you want unrelated classes to work together in a single program.
Does this make more sense ?

Abbas said...

thanks bash for clearing out d air...