OOP:什么时候是物体? [英] OOP: When is it an object?

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

问题描述

我正在尝试了解面向对象.我当然了解一点,但有时我不是100%清楚.您如何确定应将什么变成对象(另一个大整体对象的小对象部分)或什么不值得成为一个对象,或者它应该仅仅是该大整体对象的属性?

I'm trying to understand object orientation. I understand it a little bit of course, but sometimes I'm not 100% clear. How do you decide what should be turned into an object (small object part of another big whole object) or what is not worth being an object, or maybe it should be just a property of that big whole object?

对于门,我想门把手应该是一个独立的对象,但是插入钥匙的中间那部分也应该是一个独立的对象还是什么?这是一个简单的例子,所以我可以解释一下我的困惑.如果可以帮助您更好地阐述自己的观点,则可以使用您的示例.

For a door, I guess the door knob should be an independent object, but should that part in the middle where you insert the key also be an independent object or what? This is a simple example so I can explain my confusion. You can use your example if it helps you make your point better.

我当时在想,如果我打算多次使用它,应该将其作为对象.我认为这是解决此问题的实用方法,您同意吗?

谢谢

推荐答案

和往常一样,答案很不幸:这取决于...

As always, the answer is unfortunatly: it depends...

一开始,您需要某种环境,并且想要为其创建模型.但是您不会为每件事建模,而是将精力集中在重要的事情上.这就是我开始的原因:这取决于.这取决于完成任务所需的细节.

At the beginning, you have some sort of environment and you want to create a model for it. But you would not model every thing, you'll concentrate on the important things. That's why I started with: it depends. It depends on what details you need to accomplish the task.

乘坐汽车及其车轮-如果您为城市建模并需要一些交通,则可以创建一个具有属性"numberOfWheels"的"Car"类.但是,如果您设计汽车,那么您很可能也希望创建一个车轮"类,并将其中四个添加到汽车"类中.

Take the car and it's wheels - if you model a city and want some traffic, you may create a 'Car' class with the attribute 'numberOfWheels'. But if you design cars, then you most likely want to create a class 'Wheel' aswell and add four of those to the 'Car' class.

拇指法则:

  1. 如果您正在考虑的事情具有一个以上的属性,请定义一个类
  2. 如果您正在考虑的事情有某种行为,请定义一个类
  3. 如果您正在考虑的内容可能会增长或扩展,请定义一个类
  4. 如果您正在考虑的事情必须是可排序的,可比较的,请定义一个类
  5. 如果不确定,请定义一个类;)

修改

因为您强调了多次使用"方面:我认为这不是决定是否使用类的方面.想想一个简单的计数器,一个for循环中的整数值.您将使用该概念数百次,但我敢打赌,您永远也不会想到将这个可怜的小int包装到"Counter"类中-只是因为您多次使用了"counter概念".

Because you emphasized the 'multiple usage' aspect: I don't think that this is an aspect for a decision whether to use a class or not. Think of a simple counter, an integer value in a for loop. You'll use this concept hundreds of times but I bet you'll never think of wrapping this poor little int into a 'Counter' class - just because you use the 'concept of a counter' multiple times.

这篇关于OOP:什么时候是物体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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