面向对象编程-类设计的困惑 [英] Object oriented programming - class design confusion
问题描述
我正在努力将注意力集中在面向对象的编程上.
I am trying to wrap my head around object oriented programming.
我的理解是我们有对象,因此我们可以设计程序来镜像现实生活中的对象.
My understanding is that we have objects so we can design our programs to mirror real-life objects.
让我们看一个类层次结构:
Let's take a class hierarchy:
class Fruit {
void Eat() {
}
}
class Apple extends Fruit {
}
很明显,如果Eat()
是虚拟的,则可以多态使用Fruit.但这有道理吗?水果不能吃东西!
Obviously, you can use Fruit polymorphically if Eat()
is virtual. But does this make sense? Fruit cannot eat itself!
应该将水果对象传递给具有Eat()
功能的人类对象吗?
Should a fruit object rather be passed to a human object which has a Eat()
function?
我正在尝试找出思考此问题的正确方法.通常,编程对象应与现实生活的对象保持多近的距离?
I am trying to figure out the correct way to think about this. How closely, in general, should programming objects mirror real-life objects?
推荐答案
您遇到了一个设计问题-正如您正确指出的那样,Eat()作为Fruit成员的意义不大.另一方面,可食用的" 属性会更有意义.就像"onEaten"事件 一样,您的水果/苹果类所暴露的内容(以及模型中其他有意义的对象)取决于很多其他因素,包括您要尝试的因素.在您的应用程序中完成这些构造.
You've got a design problem -- as you correctly point out, Eat() doesn't make obvious sense as a member of Fruit. On the other hand, an "edible" attribute would make more sense. As would an "onEaten" event, etc. What your fruit/apple classes expose (and what other objects make sense in your model) depends on a lot of other factors, including what you're trying to accomplish with those constructs in your application.
通常,您希望您的类表示逻辑域级别的实体.有时,它们对应于现实世界中的物理实体,但在许多情况下却不对应.
In general you want your classes to represent logical domain level entities. Sometimes those correspond to a physical entity in the real world, but in many cases they don't.
在我看来,OO问题分解是程序员通常不擅长的事情.我不知道我有多少次看到过类似方向盘衍生的汽车并摇了摇头,而原始的开发人员却无法解决他们的设计为什么意义不大的问题.
In my opinion OO problem decomposition is something programmers are generally pretty bad at. I don't know how many times I've seen the equivalent of a car derived from a steering wheel and shaken my head while the original developer couldn't wrap their head around why their design didn't make a lot of sense.
这篇关于面向对象编程-类设计的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!