设计通讯录的最面向对象的方法是什么?
我问自己如何用 Java 设计一个面向对象的地址簿。
假设联系人可以有多个联系详细信息,例如地址、电话号码和电子邮件地址。
实现此目的的一种方法是为每个联系人提供每种类型的 ArrayList。但必须有更好、更面向对象的解决方案。它是什么?
I am asking myself how to design an object-oriented address book in Java.
Let's say a contact can have several contact details, like addresses, phone numbers and e-mail addresses.
One way to implement this would be to give every contact an ArrayList
for every type. But there must be a better and more object-oriented solution. What is it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我能给你的最面向对象的建议是为每个项目/信息创建一个类。例如:
最后,
这对于您的具体情况可能会也可能不会太过分,但作为一个思想实验,这是可行的方法。显然,它照顾了 OOP 的字面部分——使用对象——但也为封装、抽象和继承奠定了基础,这些都是密切相关的原则。
The most OOP suggestion I can give you is to create a class for every item/piece of information. For example:
and finally,
This may or may not be overkill for your specific case, but as a thought experiment, it's the way to go. It obviously takes care of the literal part of OOP — using objects — but also lays groundwork for encapsulation, abstraction and inheritance, which are closely related principles.
你走在正确的轨道上。我唯一会做的不同的事情是使用 List 界面 而不是 ArrayList 集合来引用联系人的属性集合。这是基于代码到接口经验法则的建议,如 这篇文章和许多其他文章。
You're on the right track. The only thing I would do differently would be to use a List interface instead of an ArrayList collection to reference the contacts' attribute collections. This is advice based on the code-to-interfaces rule-of-thumb as described in this article and many others.
我不认为这是特别非面向对象的。如果您的域允许一个
Person
可以有零个或多个EmailAddress
,那么您几乎已经准确地描述了使用列表的情况。我能想到的唯一替代方法是使用诸如此类的字段,
但在我看来,这更糟糕,因为:
其他
如果您不知道目的怎么办?)Person
拥有的属性列表现在不太干净了。我想您可以将这些属性打包到EmailContactDetails
类或其他内容中,但现在您获得了额外的间接级别(概念更复杂),但没有真正的好处。那么,如果一个人有一个可能为空、无界的电子邮件地址列表,那么将其表示为列表有什么问题呢?
I don't think that's particularly un-object oriented. If your domain is such that a
Person
can have zero or moreEmailAddress
es, then you've almost exactly described the situation to use a list.The only alternative approach I can think of would be to have fields such as
but in my opinion that's worse, because:
Other
ones? What if you don't know the purpose?)Person
has is now much less clean. I suppose you could package these properties into anEmailContactDetails
class or something, but now you've got an extra level of indirection (more conceptual complexity) for no real gain.So, if a person has a possibly-empty, unbounded list of email addresses, what's wrong with representing that as a list?
您还可以使用 Map,然后例如,通过
myMap.get("emailAdress1")
获取特定值,或者像通过myMap.entrySet()
处理列表一样迭代整个地图。You can also use a Map, and then get specific values e.g. via
myMap.get("emailAdress1")
or iterate over the whole map like you would do with a list viamyMap.entrySet()
.处理大多数用例的一种简单方法可以是这样的
One simple way to handle most of the use cases can be like this