Delegation shown simply
I Googled “simple delegation sample” and everybody wants to show UML diagrams and use long, computer-sciency words. Let’s just see a dead-simple example.
We’ll have a
NoiseMaker interface and a
Dog class that implements it (because dogs make noise). However, rather than implementing the
makeSound() method directly in
Dog, we’ll delegate to a
Fairly simple, right? Yes, there’s more code than is needed here, of course. Delegation is, unfortunately, a somewhat verbose pattern; imagine if
NoiseMaker had 10 methods and
Dog implemented all of them, simply forwarding to
Still, it’s a powerful and very useful pattern. The
Barker class lets us share common behavior, but at the same time we aren’t locked into using that class — it’s trivial to switch
Barker out with something else, or write your own override instead.
But wait, couldn’t we just subclass from
Barker? There’s nothing stopping you, but you might want to read up on Composition over Inheritance before you do so. What if you need
Dog to subclass
Animal? Wouldn’t that make more sense? But Animals don’t all bark, so you couldn’t use
Barker there…you could add a
BarkingAnimal class, but eventually, as time goes on, you’ll find yourself with a
BarkingLaughingVertebrateFartingAnimal , and it’s all downhill from there.
And that wraps it up! A simple sample and explanation of the benefits — hope it helped!
ps. For those who are using Kotlin, as I did for the example, you can use their built-in delegation keyword,
by, to remove all of the boilerplate I mentioned. In that case,
Dog would simply look like the following:
class Dog : NoiseMaker by Barker().