AS3 - 何时实施或扩展?
以多项选择题游戏为例。
您有 MathQuestion 和 WordQuestion 类,它们是否应该实现 IQuestion 接口,定义问题、答案和难度函数,或者扩展问题基类并重写这些函数是否更常见?
做这样的事情哪种方法更正确?
Take for example a multiple choice question game.
You have a MathQuestion and WordQuestion classes, should these implement an IQuestion interface, that defines say a question, answer, and difficulty functions OR is it more usual to extend a question base class, and override these functions?
Which is the more correct way of doing such things?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是思考问题的另一种方式 - 数学问题和单词问题之间实际上有什么不同吗?对我来说,听起来它们都是 Question 对象,您可以通过 composition。
您可以首先定义一个 Enum 类,其中列出了不同的测验中出现的问题类型(严格来说,ActionScript 3 没有适当的枚举,但我们仍然可以使用以下代码实现类型安全。)
然后,您可以在构造问题类时将 QuestionType 常量之一传递给问题类:
最后,客户端(使用 Question 对象的代码)可以轻松查询问题类型:
Here's another way of thinking about the problem - is there actually any different between a MathQuestion and a WordQuestion? To me, it sounds like they are both Question objects and you could differentiate between the different types via composition.
You could start by defining an Enum class which lists the different types of Questions which appear in your Quiz (strictly speaking ActionScript 3 does not have proper Enums, but we can still achieve type safety with the following code.)
You can then pass one of the QuestionType constants to the Question Class when you construct it:
Finally, a client (the code which makes use of the Question object) can query the question type easily:
这主要取决于您课程的具体细节。如果类的功能完全不同但共享函数/属性名称,那么接口会更合适。如果类共享很多公共实现,那么子类化会更合适。
根据您的描述,这两个类似乎更适合具有不同实现的“相同功能/属性”类别,并且使用接口可能会更好。
我通常使用接口来强制执行一组类共享的常见行为,而在可以通过继承的函数/属性实现严格的代码重用的情况下,更适合使用子类。归根结底,这主要是一个设计选择。
It mostly depends on the exact specifics of your classes. If the classes functionality is radically different but share function/property names then an interface would be more appropriate. If the classes share a lot of common implementation, then it would be more appropriate to subclass.
From your description, the two classes seem to fit more into the category of "same function/properties" with different implementations and would probably be better off with an interface.
I generally use interfaces are too enforce a common behavior that a group of classes share whereas sub-classing is more appropriately used in cases where you can achieve serious code re-use through inherited functions/properties. At the end of the day it's mostly a design choice.