2

I've been recently learning about design patterns and have a doubt with Decorator. For me it's pretty clear how useful it is to add extra functionality on a class method.

However, when dealing with a class that has multiple methods, all methods must be overriden even if not extended at all, ending with something like the following for each one of them:

@Override
public void whateverMethod() {
  decorated.whateverMethod();
}

Having to write this stuff for all methods (even if just two or three) seems quite unoptimal to me. Am I misunderstanding something? Is there another pattern to solve this?

markusand
  • 235
  • 7
  • 18
  • 1
    Not a pattern, but a library. [Lombok's `@Delegate`](https://projectlombok.org/features/Delegate.html) can help, but has its corner-cases in regards to generics. – Turing85 Sep 07 '20 at 19:36
  • That and most modern IDEs will generate all of those signatures for you; in some ways you could argue it's better to force them to be implemented than to let them be easily ignored – Rogue Sep 07 '20 at 19:42

1 Answers1

0

If decorating a class: prepare EmptyDecorator and use it when making more decorators

abstract class Animal {
  abstract String move();
  abstract String speak();
}

class EmptyDecorator extends Animal {
  Animal downstream;
  
  String move() {
    return downstream.move();
  }
  
  String speak() {
    return downstream.speak();
  }
}

class YourDecorator extends EmptyDecorator {
  ...
}

If decorating an interface: prepare your own interface extending that one and adding default methods:

interface Animal {
    String move();
    String speak();
}

interface EmptyDecorator extends Animal {
    Animal downstream();
    
    default String move() {
        return downstream().move();
    }

    default String speak() {
        return downstream().speak();
    }
}

class YourDecorator implements EmptyDecorator {
    Animal downstream;
    
    @Override
    public Animal downstream() {
        return downstream;
    }
}
Shadov
  • 5,421
  • 2
  • 19
  • 38
  • 1
    How is this helping? He knows how a decorator works. – Sebastiaan van den Broek Sep 07 '20 at 19:50
  • Also, this only moves the problem from the concrete decorators to the interface(s). – Turing85 Sep 07 '20 at 20:05
  • Yes, but it's reusable. You have to do this only once and you can create more decorators without all the overrides. Imagine you have 20 decorators to create, this helps you avoid repeating all this code in each one of them. – Shadov Sep 07 '20 at 21:33