什么时候使用委托而不是继承? [英] When to use delegation instead of inheritance?

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

问题描述

有人能解释一下我什么时候想使用委托而不是继承吗?

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

推荐答案

当你想复制"/公开基类的 API 时,你使用继承.如果您只想复制"功能,请使用委托.

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

这样的一个例子:您想从列表中创建一个堆栈.Stack 只有 pop、push 和 peek.您不应该使用继承,因为您不想在堆栈中使用 push_back、push_front、removeAt 等功能.

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天全站免登陆