Tuesday, June 01, 2004

Faking implementation inheritance in Java

I am a lazy programmer, and generate far too many typos. What to do when I want my objects to provide more than one interface and share the implementation amongst themselves? I could write a slew of forwarding methods, but that's sloppy and ugly and blows up the classes. I need mixins but Java doesn't have mixins. (However see here and here.) In C++ I could use implementation inheritance in the standard fashion. But what about Java?

The best I have is forwarding methods:

public interface Interface1 { void dobeedo(); } public class Bob implements Interface1 { private Interface1 mixin1; public Bob(Interface1 mixin1) { this.mixin1 = mixin1; } public void dobeedo() { mixin1.dobeedo(); } }

Sure it works, but do you really want to do this for several large interfaces? Poor Bob gets rather cluttered rather quickly.

(NB — What pattern is this? I can't quite put my finger on it. I don't mean the dependency injection, but the forwarding.)

Post a Comment