Friday, January 29, 2010

The Adapter Pattern

Note: The word client and caller are used interchangeably in this document which both refer to the class/method which calls the method of another class.


About : Being adaptive is at the core of any human activity which requires a person to become conversant to the changing environment. And surprisingly OOP also comes under the same category!!. Many times it happens that the class or interface we are using is not,for any particular reason , compliant with the one which client expects. In such cases the adapter pattern can come to our rescue. It is recommended that you use this pattern wisely in order to avoid unexpected results.

Definition :converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interface.

When to use it: We can use this pattern when, due to compatibility issues the caller does not identify our interface as the one expected by it. Let's say, we have a library provided by our client which expects some interface and your company has ,in past, developed some libraries. Now, in order for our libraries to be used by client-provided libraries they must be compatible. What this pattern does is they MAKE the client SEEM that it is compatible.

How to use it : All we need to do is, create a concrete class which implements the interface which client expects and, delegate the request to the concrete class which implements the interface, which we need to function in response.

Example : The diagram 1.1 illustrates how the request came for a target interface gets delegated to another interface. Here, the client only “looks” at the interface being implemented.

To make the pattern more clear, let's understand it with a real world(confined to Java) example.

We have nice collection interfaces, java.util.Enumeration and java.util.Iterator. Both having methods to iterate through the objects of any of the java.util.Collection subclasses. Now,through the use of Adapter Pattern, we can create an adapter which makes client seem, if not actually make, the objects of java.util.Iterator compatible with objects of java.util.Enumeration. Diagram 1.2 below shows the class diagram for the same.

Conclusion : To summarize, when the “type” expected by the client differs from the one we have, use this pattern. To make components more adaptive,which might not have been otherwise , we can use this pattern to suit to our need.

Any suggestions or queries are welcomed.

No comments:

Post a Comment