CSE Roadmap

Core tier · about 3 hours · 7 parts

Part 5 of 7 · 1 min read

Delegation

A way to make composition as strong as inheritance.

GoF also describes delegation: one object handles a request by passing it to another, the delegate. It is like a subclass deferring to its parent. A difference is that an inherited method can use this to refer to the receiving object, so to get the same effect through delegation, the receiver hands itself over as an argument when the delegate needs it.

GoF's example: instead of making Window a subclass of Rectangle just because windows are rectangular, Window keeps a Rectangle and delegates the area calculation to it. At run time, the window becomes circular by swapping in a Circle, as long as both have the same type.

GoF adds a caution. Delegation, like other flexible designs, makes software harder to follow than a static one. It is worth using only when it removes more difficulty than it adds, and it works best inside well-known patterns. Several patterns in Level 4 use it, including Strategy and State.

Check yourself: 1. What does Window hold in the example? 2. How does a window become circular at run time? 3. When is delegation a good choice?