Tuesday, May 8, 2012

Adapter Pattern : Nice article

  • http://www.oodesign.com/adapter-pattern.html
  •  Convert the interface of a class into another interface clients expect.
  • Adapter lets classes work together, that could not otherwise because of incompatible interfaces.
 
 Adapter  Pattern Implementation - UML Class Diagram
The classes/objects participating in adapter pattern:

  • Target - defines the domain-specific interface that Client uses.
  • Adapter - adapts the interface Adaptee to the Target interface.
  • Adaptee - defines an existing interface that needs adapting.
  • Client - collaborates with objects conforming to the Target interface.

Objects Adapters - Based on Delegation

Objects Adapters are the classical example of the adapter pattern. It uses composition, the Adaptee delegates the calls to Adaptee (opossed to class adapters which extends the Adaptee). This behaviour gives us a few advantages over the class adapters(however the class adapters can be implemented in languages allowing multiple inheritance). The main advantage is that the Adapter adapts not only the Adpatee but all its subclasses. All it's subclasses with one "small" restriction: all the subclasses which don't add new methods, because the used mechanism is delegation. So for any new method the Adapter must be changed or extended to expose the new methods as well. The main disadvantage is that it requires to write all the code for delegating all the necessary requests tot the Adaptee.

Class Adapters - Based on (Multiple) Inheritance

Adapter  Pattern Implementation - UML Class Diagram
Class adapters can be implemented in languages supporting multiple inheritance(Java, C# or PHP does not support multiple inheritance). Thus, 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. There are advantages and disadvantages:
  • It adapts the specific Adaptee class. The 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 for delegation, which must be written for an Object Adapter.
If the Target is represented by an interface instead of a class then we can talk about "class" adapters, because we can implement as many interfaces as we want.

Adapter Pattern and Strategy Pattern

Adapter Pattern and Strategy Pattern - there are many cases when the adapter can play the role of the Strategy Pattern. If we have several modules implementing the same functionality and we wrote adapters for them, the adapters are implementing the same interface. We can simply replace the adapters objects at run time because they implements the same interface.

No comments:

Post a Comment