Implementing Class Adapter Pattern in Java

前端 未结 5 1080
失恋的感觉
失恋的感觉 2020-12-09 20:47

While reading up on the Class Adapter pattern in Head First Design Patterns, I came across this sentence:

class adapter... because you need multiple i

相关标签:
5条回答
  • 2020-12-09 21:14

    Yes, you can create a class adapter with an interface as long as you're only wrapping a single adaptee. With multiple inheritance you could take two or more adaptees and wrap them into a single interface.

    0 讨论(0)
  • 2020-12-09 21:23

    Class Adapters are kind of possible in Java by using single inheritance. As an example from Design pattern for dummies, suppose we have to adapt AWT checkboxes to be used alongside with Swing checkboxes, we can write a class adapter for this.

    The UI code in Swing to determine if a check box is checked is done with the isSelected method. But, AWT check boxes dont support isSelected(), they use getState() instead.

    So we can write an adapter to wrap an SWT check box and adapt the getState() to isSelected()

      public class CheckboxAdapter extends Checkbox
      { 
    
          public CheckboxAdapter(String n) 
          {
             super(n);
          }
    
          public boolean isSelected()
          {
             return getState();
          }
      }
    

    Now we can handle AWT adapted check boxes as we would standard Swing check boxes when it comes to the isSelected method.

      public void itemStateChanged(ItemEvent e)
      {
          String outString = new String("Selected: ");
    
          for(int loopIndex = 0; loopIndex 
             <= checks.length - 1; loopIndex++){
               if(checks[loopIndex].isSelected()) {
                  outString += " checkbox " + loopIndex;
               }
           }
          text.setText(outString);
       }
    

    EDIT: True class adapter are not possible in Java, if they were we could inherit from multiple classes, which we want to mimic in an adapter class.

    Also see http://www.journaldev.com/1487/adapter-design-pattern-in-java-example-tutorial for two examples in Java using Class Adapter and Object adapter, to achieve same result.

    0 讨论(0)
  • 2020-12-09 21:27

    The full story in heads up is: class adapter pattern is impossible in Java just because Java does not provide multiple inheritance.

    In their diagram, they show that the Adapter class subclasses both Target and Adaptee. Your example is (close to) the Object adapter pattern. The difference is that you implement the Target in your adapter class, rather then just subclassing the target (MyNeededInterface in your example)

    0 讨论(0)
  • 2020-12-09 21:35

    GoF (Gang of Four) tells us about two major kinds of adapters:

    A. Class adapters. They generally use multiple inheritance to adapt one interface to another. (But we must remember, in java, multiple inheritance through classes is not supported (for a good reason :) ). We need interfaces to implement the concept of multiple inheritance.)

    B. Object adapters. They depend on the object compositions.

    To illustrate the concepts, I'll present a simple example: (source: book Java Design Patterns)

    interface IIntegerValue 
    {
        public int getInteger();
    }
    
    class IntegerValue implements IIntegerValue
    {
        @Override
        public int getInteger() 
        {
            return 5;
        }
    }
    // Adapter using interface
    class ClassAdapter extends IntegerValue
    {
        //Incrementing by 2
        public int getInteger()
        {
            return 2 + super.getInteger();
        }
    }
    
    // Adapter using composition
    class ObjectAdapter implements IIntegerValue
    {
        private IIntegerValue myInt;
    
        public ObjectAdapter(IIntegerValue myInt)
        {
            this.myInt=myInt;
        }
    
        //Incrementing by 2
        public int getInteger()
        {
            return 2+this.myInt.getInteger();
        }
    }
    
    class ClassAndObjectAdapter
    {
        public static void main(String args[])
        {
            System.out.println("Class and Object Adapter Demo");
            ClassAdapter ca1=new ClassAdapter();
            System.out.println("Class Adapter is returning :"+ca1.getInteger());
            ClassAdapter ca2=new ClassAdapter();
            ObjectAdapter oa=new ObjectAdapter(new IntegerValue());
            System.out.println("Object Adapter is returning :"+oa.getInteger());
        }
    }
    

    Console output:

    Class and Object Adapter Demo
    Class Adapter is returning :7
    Object Adapter is returning :7

    0 讨论(0)
  • 2020-12-09 21:36

    The class adapter pattern is not possible in Java because you can't extend multiple classes. So you'll have to go with the adapter pattern which uses composition rather than inheritance.

    An example of the adapter pattern through composition can be found below:

    interface Duck
    {
        public void quack();
    }
    
    class BlackDuck implements Duck
    {
       public void quack() { }
    }
    
    class Turkey
    {
        public void gobble() { }
    }
    
    class TurkeyAdapter implements Duck
    {
        private Turkey t;
    
        public TurkeyAdapter(Turkey t)
        {
            this.t = t;
        }
    
        public void quack()
        {
            // A turkey is not a duck but, act like one
            t.gobble();
        }
    }
    

    Now you can pass a Turkey to a method which is expecting a Duck through the TurkeyAdapter.

    class DuckCatcher
    {
        public void catch(Duck duck) { }
    }
    

    By using the adapter pattern the DuckCatcher is now also able to catch Turkey(Adapter)s and Ducks.

    0 讨论(0)
提交回复
热议问题