Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- I'd like to point out something that bit me in the behind, coming from C++ where you can easily inherit many implementations too.
- 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.
- For instance:
- interface Herbivore {
- void munch(Vegetable v);
- };
- interface Carnivore {
- void devour(Prey p);
- }
- interface AllEater : public Herbivore, Carnivore { };
- class Fox implements AllEater {
- ...
- };
- class Bear implements AllEater {
- };
- In this example, Fox and Bear cannot share a common base implementation for both it's interface methods `munch` and `devour`.
- If the base implementations look like this, we'd maybe want to use them for `Fox` and `Bear`:
- class ForestHerbivore implements Herbivore
- void munch(Vegetable v) { ... }
- };
- class ForestCarnivore implements Carnivore
- void devour(Prey p) { ... }
- };
- 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:
- class Fox implements AllEater {
- private ForestHerbivore m_herbivore;
- private ForestCarnivore m_carnivore;
- void munch(Vegetable v) { m_herbivore.munch(v); }
- void devour(Prey p) { m_carnivore.devour(p); }
- }
- This gets unwieldy if interfaces grow (i.e. more than 5-10 methods...)
- A better approach is to define an interface as an aggregation of interfaces:
- interface AllEater {
- Herbivore asHerbivore();
- Carnivore asCarnivore();
- }
- 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.
- Less coupling this way.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement