什么是代表团?我什么时候想用它? [英] What is delegation? When would I want to use it?
问题描述
在OOP中,提到了一个术语委托。这是如何在课堂上建模的?我在雅虎等搜索,但获得了代表的链接。
In OOP, a term delegation is mentioned. How is this modelled in a class? I searched on yahoo etc but got links to delegates.
推荐答案
想象你有课程 code>和
引擎
:
public class Car {
private Engine engine = new Engine(); //or inject it externally
public void start() {
engine.start();
}
}
在这个例子中, Car
委托给底层的引擎
。汽车的用户不能直接启动发动机(除非他是机械师)。但是他可以告诉汽车启动,而汽车依次告诉发动机启动。
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.
这篇关于什么是代表团?我什么时候想用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!