何时使用代理而不是继承? [英] When to use delegation instead of inheritance?

查看:124
本文介绍了何时使用代理而不是继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释什么时候我想使用代理而不是继承?

解决方案

当你想复制 /暴露基类'API,你使用继承。
当您只想复制功能时,请使用委托。



其中一个示例:
您要创建一个名单。堆栈只有流行,推,偷看。您不应该使用继承,因为您不希望在堆栈中push_back,push_front,removeAt等功能。


Could someone please explain when would I want to use delegation instead of inheritance?

解决方案

When you want to "copy"/Expose the base class' API, you use inheritance. When you only want to "copy" functionality, use delegation.

One example of this: You want to create a Stack out of a List. Stack only has pop, push and peek. You shouldn't use inheritance given that you don't want push_back, push_front, removeAt, et al.-kind of functionality in a Stack.

这篇关于何时使用代理而不是继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆