设计类的问题
我有一个类,如下所示,
public class Book extends Item{ ...}
public class DVD extends Item{ ...}
书籍的类型可以是参考或问题。 DVD 只能是 ISSUE 类型。
那么我应该按如下方式创建 Item 吗?
public class Item {
public enum ItemType{REFRENCE,ISSUE};
ItemType itemtype;
}
或者我应该为书籍和 DVD 声明单独的枚举?
I have a classes as below
public class Book extends Item{ ...}
public class DVD extends Item{ ...}
Book can be of type REFRENCE or ISSUE.
DVD can be of type ISSUE only.
So should I create Item as follows?
public class Item {
public enum ItemType{REFRENCE,ISSUE};
ItemType itemtype;
}
Or I should declare seperate enum for both book and DVD?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
定义两个接口
Reference
和Issue
怎么样,Book
将实现这两个接口,而DVD
将仅实现Issue ?
How about defining two interfaces
Reference
andIssue
andBook
will implement both whileDVD
will implement onlyIssue
?这取决于。 DVD ISSUE 与书籍ISSUE 相同吗?
如果是这样,则将其放入父类中,并在创建 REFERENCE DVD 时引发异常。
如果不是,则在两个子类中定义单独的公共枚举。
It depends. Is a DVD ISSUE the same as a book ISSUE?
If so then put it in the parent class and throw an exception if you create a REFERENCE DVD.
If it isnt then define seperate public enums in the two subclasses.
通过将某些类型存储在枚举中,您将反对使用该语言的面向对象功能。
另外,我不认为“项目”“具有”作为问题/参考的属性。它更像是一种“是”关系,这表明您应该使用继承/接口。
当然,正确的方法取决于您的程序的用途。有时,面向对象的构造可能会妨碍您。
By storing something's type in an enum you are going against using the object oriented features of the language.
Also, I don't feel that an "item" "has a" property of being an issue/reference. It's more of an "is a" relation, which suggests you should use inheritence/interfaces.
Of course the right approach depends on what your program is meant to do. Sometimes object oriented constructs can get in your way.