Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is delegation? When would I want to use it?

In OOP, a term delegation is mentioned. How is this modelled in a class? I searched on yahoo etc but got links to delegates.

like image 974
GurdeepS Avatar asked Jan 15 '11 18:01

GurdeepS


1 Answers

Imagine you have the classes Car and Engine:

public class Car {
   private Engine engine = new Engine(); //or inject it externally

   public void start() {
       engine.start();
   }
}

In this example the Car delegates to the underlying Engine. The user of the car cannot directly start the engine (unless he is a mechanic). But he can tell the car to start, and the car in turn tells the engine to start.

You'd want to use it whenever you use object composition and you need to use a method of one of the composing objects. In that case you create a method that delegates to it.

like image 116
Bozho Avatar answered Oct 08 '22 15:10

Bozho