如何决定是否应将其分为 2 个类或保留在同一类中?
我有一个页面,其中列出了一些项目。每个项目都有一些属性:评论、图像、标题、评论表单和内容。创建一个名为 item
的类来表示列表中的单个项目似乎很简单。
但是,我还有一个“孤立”项目,用于将新项目添加到列表中。例如,它具有所有相同的属性、文本框、按钮等,用于添加图像、写入内容等,但它不存储在数据库中,并且它有一个新的“添加”按钮,可将其保存到数据库中,并且它的然后添加到列表中。
我是否应该仍然只创建 1 个名为 item
的类,并且只有一个名为 isSaved
的属性来确定是否显示“添加”按钮,是否显示评论表单它,等等?
或者我应该创建 2 个单独的类,调用一个 newItem
并将其用于孤立项目,另一个 savedItem
并将其用于数据库中已有的项目?
另外,这是在 javascript 中,所以我认为我不能使用太多继承。
I've got a page with a list of some items. Each item has got some properties: comments, images, a title, a comments form, and content. It seems simple enough to create a class called item
which will represent a single item in the list.
However, I've also got an 'orphaned' item which is used for adding new items to the list. E.g, it has got all the same properties, textboxes, buttons, etc for adding images, writing the content, etc but its not stored in the db, and it has got a new 'add' button which saves it to db, and its then added to the list.
Should I still create just 1 class called item
and just have a property called something like isSaved
to determine whether to show the 'Add' button, whether to show the comment form for it, etc?
Or should I create 2 seperate classes, call one newItem
and use it for the orphaned item, and another savedItem
and use it for the items which are already in the db?
Also, this is in javascript so I don't think I can use much inheritance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,当行为或属性需要更改时,您可以创建子类。如果唯一的区别是对象是否保存到数据库中,则很可能该对象不是子类的候选者。添加诸如
isSaved
之类的属性可能是最好的选择。也就是说,除非一个人在得救/未得救时的行为与另一个人根本不同。In general, you subclass when behavior or properties need to change. If the only difference is whether the object is saved to the DB or not, most likely, that is not a candidate for a subclass. Adding a property such as
isSaved
would probably be the best bet. Unless, that is, the behavior of one is fundamentally different from the other when it is saved/unsaved.