Wednesday, August 4, 2010

Adapter Design Pattern

Adapter is used to adapt the behavior/functionalities of an existing class but with a different interface.
It can be implemented by two ways, by inheritance (also called class adapter) or by composition (also called object adapter). Either we can extend the existing class and use its functionalities in new interface method, or we can use a reference of existing class in new object for using existing functionalities. 

Example

  • We are making data bound UI components, which are implementing some of our proprietary interface to support the data loading/unloading. But UI components are already defined with Swing library so we want to use these and just want to bind them with data sources. Here we can extend our new components from existing Swing component and implement our data binding interface to it.
  • Use of Window Adapter while intercepting the window closing event. 



When to use

  • Sometime in our system, we use any class/interface whose some/most of the functionalities are already defined with any other existing class.  But due to system protocol, we have to use only new class probably with some new functionality. Here we can apply adapter pattern to adapt the behavior of existing class but with new interface. 

Usage

  • Can use the functionalities of existing classes but with new interface without re-implementing it.
  • Object adapter even help to adapt the sub-class implementations of a class by simply referring it. 


Drawbacks

  • Class adapter won’t work when we want to adapt a class and all of its sub classes because we need to derive the class from adapted classes while creating the new class. 

No comments:

Post a Comment