Tuesday, October 26, 2010

Adapter

A method to make use of legacy code or different interface, by means of adapting it to required interface. We go for adapter pattern when the consumed class is not in this developers control as against the bridge pattern where a common interface is agreed.
In java its object adapter pattern, where the adapter will have a reference to the legacy class.

Legacy interface
public class LegacyActionPerformer {

    public void performAction(String action){
        System.out.println("Performing action: "+action);
    }
} 
New Interface
 public interface INewActionPerformer {

    public void performNewAction(String action);
}
Adapter
public class ActionAdapter implements INewActionPerformer{

 private LegacyActionPerformer performer=new LegacyActionPerformer();

 public void performNewAction(String action) {
  performer.performAction(action);
  
 }
}
Client
public class AdapterClient {

    public static void main(String...strings ){
        new ActionAdapter().performNewAction("create a new world");
    }
} 

No comments:

Post a Comment