Java Design Patterns Adapter Patterns class adapter vs object adapter

Introduction

Class adapters generally use multiple inheritance to adapt one interface to another.

In Java we need interfaces to implement the concept of multiple inheritance.

Object adapters depend on the object compositions.

Example

interface Job {/*from ww  w  . jav  a  2s.  c  o m*/
   public int doJob();

}

class IntegerJob implements Job {
   @Override
   public int doJob() {
      return 5;
   }
}

class ClassAdapter extends IntegerJob {
   public int doJob() {
      return 2 + super.doJob();
   }
}

class ObjectAdapter {
   private Job myInt;

   public ObjectAdapter(Job myInt) {
      this.myInt = myInt;
   }

   public int getInteger() {
      return 2 + this.myInt.doJob();
   }
}
public class Main {
   public static void main(String args[]) {
      ClassAdapter ca1 = new ClassAdapter();
      System.out.println("Class Adapter:" + ca1.doJob());

      ObjectAdapter oa = new ObjectAdapter(new IntegerJob());
      System.out.println("Object Adapter:" + oa.getInteger());
   }
}



PreviousNext

Related