我应该扩展ArrayList(is-a)还是应该将其作为成员包含(has-a)? [英] Should I extend an ArrayList (is-a) or should I include it as a member (has-a)?

查看:176
本文介绍了我应该扩展ArrayList(is-a)还是应该将其作为成员包含(has-a)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个维护数字列表的简单程序,我希望这个列表也有一个名字。哪种方法最好:让我的列表类扩展ArrayList还是让它包含一个ArrayList成员?在这两种情况下,当然都会有一个名称字符串成员。

I'm making a simple program that maintains a list of numbers, and I want this list to also have a name. Which is the best approach: have my list class extend ArrayList or have it include an ArrayList member? In both cases, there would of course be a "name" String member.

第一种方法意味着我只需要实现一个getter&这个名字的setter,但我认为这会使我的课程与特定的实现过于紧密联系?例如,如果我想稍后使用Vector,那么我必须在任何地方更改代码。

The first approach means I only have to implement a getter & setter for the name, but I think this would tie my class too closely to a particular implementation? For example, if I wanted to later use a Vector, than I would have to change code everywhere.

第二种方法可以更容易地更改实现,但是当然,因为我必须实现一堆包装器,所以当然变得非常讨厌。

The second approach would make it easier to change the implementation, but of course becomes quite annoying for now, since I have to implement a bunch of wrappers.

我已经阅读了关于继承与组合的SO帖子,因为我的列表是一种ArrayList,我倾向于第一种方法。但是,讨论是否存在任何差异,因为我正在扩展Collection类vs扩展通用类?或者我是否过度思考?

I've read the SO posts regarding inheritance vs. composition, and since my list is a type of ArrayList, I am leaning towards the first approach. However, is there any differences to the discussion because I'm extending a Collection class vs extending a general class? Or am I over-thinking this?

推荐答案

两者都不是更好,这是你提到的权衡。

Neither is better, its a trade-off as you mentioned.

如果你进行聚合(has-a),你必须包含你将要使用的成员的所有功能(即实现调用它们的函数)

If you do aggregation (has-a) you have to wrap all the functionality of the member you're going to use (i.e implement functions that call them)

如果你继承了,很多函数都会添加到你的新类中,这可能是不必要的,你也需要实现抽象函数。

If you do inheritance, A lot of functions are added to your new class which might be unneccessary, And you need to implement abstract functions as well.

如果您在C ++环境中,私有继承将是一个选项,但这里有利有弊

If you were in a C++ environment, private inheritance would be an option, But here both have pros and cons

这篇关于我应该扩展ArrayList(is-a)还是应该将其作为成员包含(has-a)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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