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

风流意气都作罢 提交于 2019-12-19 17:41:47

问题


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


回答1:


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.




回答2:


Delegation is like inheritance except instead of class2 having copied functions and variables from class1 class2 just gets class1 to do that stuff for it and class2 focuses on doing and having the extra functions and variables you give it. One obvious advantage of this is it saves space on your computer.



来源:https://stackoverflow.com/questions/4701418/what-is-delegation-when-would-i-want-to-use-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!