Wednesday, June 02, 2004

More on delegation

Of course the word I was searching for yesterday was delegation. But there are three flavors of implementation inheritance given:

public interface Bob { void dodeedo(); }
Your basic class inheritance
public class Fred extends BobImpl { }
Typical delegation
public class Fred implements Bob { private Bob bob = new BobImpl(); public void dobeedo() { bob.dobeedo(); } }
Returning the interface
public class Fred { private Bob bob = new BobImpl(); public Bob bob() { return bob; } }

Only in C++ is the first very flexible by using a template parameter to vary the implementing base class. Most code I see does the second, but this falls down when you provide several interfaces, especially when they are poorly designed to fit together such as List and Map. The third is the most flexible and resembles interface discovery. One could code it that way:

public class Fred { private Bob bob = new BobImpl(); public Object discover(Class itf) { if (itf.isAssignableFrom(Bob.class)) return bob; else return null; // alternatively throw something like ClassCastException } }

But that is way overkill most of the time.

Post a Comment