Pages

Tuesday, July 24, 2012

Adapter design pattern in Java with example


This is a structural design pattern. A Wrapper class, i.e., Adatper class is used to convert requests from it to Adaptee class.

The Adapter pattern converts the interface of a class into another interface the client expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

Two forms of Adapter pattern:
1) class adapter (uses inheritace)
2) object adapter (uses composition)

object adapter 
---------------------
object adapter design pattern



 
A simple example
of object adapter pattern:

Client expecting the Target as duck, but there's turkey at the end. So we'll create a Duck interface as the Target and TurkeyAdapter as the adapter class that implements the Duck interface.
So whenever client class calls the Duck's quak() method, it'll internally call Turkey's gobble() method. i.e., a request() to a specificRequest().

ITurkey.java
package com.sample.adp;

public interface ITurkey {
 public void gobble();
}

WildTurkey.java
package com.sample.adp;

public class WildTurkey implements ITurkey {
 public void gobble() {
  System.out.println("gobble...gobble...!!!");
 }
}

IDuck.java
package com.sample.adp;

public interface IDuck {
 public void quack();
}

TurkeyAdapter.java
package com.sample.adp;

public class TurkeyAdapter implements IDuck {

 ITurkey t;
 public TurkeyAdapter(final ITurkey t) {
  this.t = t;
 }
 
 @Override
 public void quack() {
  t.gobble();
 }
}

Client.java
package com.sample.adp;

public class Client {
 public static void main(String[] args) {
  WildTurkey t = new WildTurkey();
  IDuck ta = new TurkeyAdapter(t);
  ta.quack();
 }
}

output:
gobble...gobble...!!!

1 comment: