什么是委托?我什么时候想使用它?
在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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您有类
Car
和Engine
:在此示例中,
Car
委托给底层Engine
。汽车的使用者不能直接启动发动机(除非他是机械师)。但他可以告诉汽车启动,汽车反过来又告诉发动机启动。每当您使用对象组合并且需要使用组合对象之一的方法时,您都希望使用它。在这种情况下,您创建一个委托给它的方法。
Imagine you have the classes
Car
andEngine
:In this example the
Car
delegates to the underlyingEngine
. 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.
委托就像继承,只不过 class2 不是从 class1 复制函数和变量,class2 只是让 class1 为它做这些事情,而 class2 专注于执行并拥有你给它的额外函数和变量。这样做的一个明显优点是它可以节省计算机空间。
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.