Delegation Pattern

Posted by

What is it?
Example Problem
Solution (design)
Code
Why?

What is it?

Chances are if you have used AWT1.1 or Swing, you have already used the delegation pattern, you just didn’t know you were doing it. The delegation pattern can be defined as follows. When you are creating a class that does everything another class does and more, then instead of subclassing the other class, you have to declare it as a data member or property of your class.

Example Problem

Lets say you are writing a class (ClassA) that does what another class (ClassB) does. ClassA also has to do more things (have more methods) than what ClassB does. You might be tempted to simply have ClassA subclass ClassB. Resist this temptation, becuase it is the wrong thing to do. Inheritance is inherently slow, and is a very strong linkage in your design. As a rule you want to create loosely coupled, but strongly coherent systems.

Solution (design)

The correct design involves defining a data member of type ClassB in ClassA. This way, you have eliminated the need for subclassing and reduced the coupling strength. In fact, ClassB might just be an interface, which is even better for loose coupling.

Code

 1: //ClassA
 2: public class ClassA{
 3:     //data
 4:     private ClassB classB;
 5:
 6:     //methods
 7:     public void doThis(){classB.doThis();}
 8:     public void doThat(){…}
 9: }
 1: //ClassB
 2: public class ClassB{
 3:     public void doThis(){…}
 4: }

Why?

The delegation pattern allows your code to be loosely coupled, which is a very important goal of any object oriented system. It is easy to get this pattern confused with the adapter pattern, they are similar, but completely different. Study both patterns carefully and you will see how they are totally different (yet similar).