Traits 可以用来在 Scala 中构建游戏组件系统吗?
我只是想知道使用特征来构建游戏对象在语义上是否正确。一方面,我将其视为具有关系(对象具有组件),但另一方面,我将组件视为组成对象。
例如。你有一个游戏对象。游戏对象本身几乎不执行任何操作,但混合到其中的东西会赋予它额外的属性。组件可以是 HealthComponent(有生命值)、PhysicsComponent(模拟物理)、ClickableComponent(可以点击)。
我喜欢使用特征的想法,因为所有属性和方法都添加到原始对象上,并且我可以执行 player.getHP
而不是 player.getHealthComponent.getHP
。另一方面,我发现使用特征的命名和语义很奇怪。 trait HealthComponent extends GameObject
- 这没有意义。 HealthComponent
属于 GameObject,它不满足 extend
隐含的是关系。我假设特征通常被视为其父类的特殊版本是否正确?如果是这样,我该如何命名类似上面的对象?
I'm just wondering if it is semantically correct to use traits to build game objects. On one hand, I view this as a has a relationship (an object has components), but on the other hand I view components as composing an object.
For example. You have a GameObject. A GameObject does pretty much nothing on its own, but the things you mix into it give it additional properties. Components could be HealthComponent (has health), PhysicsComponent (simulates physics), ClickableComponent (can be clicked).
I like the idea of using traits because all of the properties and methods are added on the original object and I can do player.getHP
instead of player.getHealthComponent.getHP
. On the other hand, I find the naming and semantics of using traits weird. trait HealthComponent extends GameObject
- this doesn't make sense. A HealthComponent
belongs to a GameObject, it doesn't fulfill the is a relationship that's implied by extend
. Am I correct in assuming that traits are normally treated as specialized versions of their parent class? If so, how would I name something like the above object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
补充 @Moritz 的回答,也可以堆叠相关行为而不从超类型继承实现:
To supplement @Moritz's answer, it's also possible to stack related behaviors without inheriting implementation from the super type:
如果你想限制你的特征可以混合的类型,你可以将依赖关系表达为自类型:
这样你的特征就不会扩展
GameObject
,但只能用作子类型的混合游戏对象
。另请参阅了解 Scala 的蛋糕模式和链接的文章。
If you want to restrict the types your trait can be mixed in you can express the dependency as a self-type:
This way your trait does not extend
GameObject
but can only be used as a mixin for subtypes ofGameObject
.See also Understanding Scala's Cake Pattern and the linked article.
“
trait HealthComponent
extends GameObject- 这没有意义。
HealthComponent`属于 GameObject” - 你想要的是自我类型 ,并根据蛋糕模式进行构建:所以你有
“我正确吗 ?假设特征通常被视为其父类的特殊版本?” ——我不会这么说。如果您采用如上所述的自下而上的方法,您不会认为特征是某些父母的子类型,而是相反(较大的组件由特征组成并由特征专门化)
"
trait HealthComponent
extends GameObject- this doesn't make sense. A
HealthComponent` belongs to a GameObject" -- what you want is self types, and building according to the cake pattern:So you have
"Am I correct in assuming that traits are normally treated as specialized versions of their parent class?" -- I wouldn't say so. If you go for a bottom-up approach like the above, you don't think so much as traits being subtypes of some parents, rather the other way round (larger components being composed of and specialised by traits)