The Adapter Pattern

This pattern comes under Structural Patterns category.

Also known as Wrapper Pattern.

The Adapter pattern lets you use an existing class to meet a client class’s needs. When a client specifies its requirements in an interface, you can usually create a new class that implements the interface and subclasses an existing class. This approach creates a class adapter that translates a client’s calls into calls to the existing class’s methods. This chapter will introduce you to the Adapter pattern in Java.

–InformIT.com(http://www.informit.com/articles/article.aspx?p=481863)

when developers write web services , they expose only the interfaces to the public(clients), but not the service implementations.But when clients need to consume those  services, they use the service  interfaces to access the services .Sometimes clients feel the service interfaces are not compatible for their usage.Fox ex consider

public interface EmployeeInfo {

public List getEmpNames();

} Assume the developers has already written the implementation class for this and they had exposed this interface to their clients.

Suppose some client wants only the employee first names , then the client feels that this interface is incompatible for its usage as this is returning employees full names  ,

(i) Also developers can’t change the implementation now , because they had already deployeed the service ,

(ii) Another drawback is we cannot add  a new method getEmpFirstNames() in the interafce , because all the sb classes who depend on this interface has to unnecessarily implement this new method.

thats where the Adapter Pattern comes into picture.

Participents: Client, Target,Adapter,Adoptee.

There are 2 types of implementing Adpter Patterns

Class Adapter: uses multiple inheritance for adopting interfaces one into another

Object Adapter: users class composition for adopting interfaces.

The general  call flow will look like this.

When to use?

Use the Adapter pattern when

  • you want to use an existing class, and its interface does not match the one you need.
  • you want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don’t necessarily have compatible interfaces.
  • (object adapter only) you need to use several existing subclasses, but it’s impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class.

Consequences:

Follow

Get every new post delivered to your Inbox.