Using AOP is already a good answer; that was my first idea.
I tried to find a good way to do this without AOP, although I came up with this idea (using the Decorator template):
interface I { String method1(); String method2(); ... String methodN(); } class IDoSomethingDecorator implements I { private final I contents; private final Runnable commonAction; IDoSomethingDecorator(I decoratee, Runnable commonAction){ this.contents = decoratee; this.commonAction = commonAction; } String methodi() { this.commonAction().run(); return contents.methodi(); } }
Then you can decorate the construct A (which implements I):
I a = new IDoSomethingDecorator(new A(),doSomething);
It’s basically not rocket science, but actually the result is more code than your first idea, but you can introduce a general action and you separate the additional action from class A. In addition, you can easily disable it or use it only in tests , eg.
Michael Schmeißer
source share