Advertisement
Guest User

Untitled

a guest
May 15th, 2013
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.92 KB | None | 0 0
  1. I'd like to point out something that bit me in the behind, coming from C++ where you can easily inherit many implementations too.
  2.  
  3. Having a "wide" interface with many methods means that you'll have to implement a lot of methods in your concrete classes and *you can't share these easily* across implementations.
  4.  
  5. For instance:
  6.  
  7.    interface Herbivore {
  8.        void munch(Vegetable v);
  9.    };
  10.  
  11.    interface Carnivore {
  12.        void devour(Prey p);
  13.    }
  14.  
  15.    interface AllEater : public Herbivore, Carnivore { };
  16.  
  17.    class Fox implements AllEater {
  18.        ...
  19.    };
  20.  
  21.    class Bear implements AllEater {
  22.    };
  23.  
  24. In this example, Fox and Bear cannot share a common base implementation for both it's interface methods `munch` and `devour`.
  25.  
  26. If the base implementations look like this, we'd maybe want to use them for `Fox` and `Bear`:
  27.  
  28.    class ForestHerbivore implements Herbivore
  29.        void munch(Vegetable v) { ... }
  30.    };
  31.  
  32.    class ForestCarnivore implements Carnivore
  33.        void devour(Prey p) { ... }
  34.    };
  35.  
  36. But we can't inherit both of these. The base implementations need to be member variables in the class and methods defined can forward to that. I.e:
  37.  
  38.     class Fox implements AllEater {
  39.         private ForestHerbivore m_herbivore;
  40.         private ForestCarnivore m_carnivore;
  41.  
  42.         void munch(Vegetable v) { m_herbivore.munch(v); }
  43.         void devour(Prey p) { m_carnivore.devour(p); }
  44.     }
  45.  
  46. This gets unwieldy if interfaces grow (i.e. more than 5-10 methods...)
  47.  
  48. A better approach is to define an interface as an aggregation of interfaces:
  49.  
  50.    interface AllEater {
  51.         Herbivore asHerbivore();
  52.         Carnivore asCarnivore();
  53.    }
  54.  
  55. This means that Fox and Bear only has to implement these two methods, and the interfaces and base classes can grow independetly of the aggregate `AllEater` interface that concerns the implementing classes.
  56.  
  57. Less coupling this way.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement