简体   繁体   English

面向对象设计-游戏

[英]Object Oriented Design - Game

I'm designing a Game with Java, there are 2 players, different types of enemies and potions. 我正在用Java设计游戏,有2个玩家,不同类型的敌人和药水。 This is my classes hierarchy: 这是我的班级层次结构:

在此处输入图片说明

As you can see I have the Touchable interface, I know interfaces are contracts with classes that describe a certain behavior of the class, so I declared the void collision(Player p) method inside the Touchable interface because not every GameObject is Touchable (by the player) but then I realized something, I can put the void collision(Player p) method in the GameObject class this way: 如您所见,我拥有Touchable接口,我知道接口是与描述类特定行为的类的契约,因此我在Touchable接口内声明了void collision(Player p)方法,因为并非每个GameObject都是Touchable(通过玩家),但后来我意识到,我可以通过以下方式在游戏对象类中添加void collision(Player p)方法:

public void collision(Player p) {}

and then get rid of the Touchable interface, and get rid of this if statement in the for each loop over all the GameObjects: 然后摆脱Touchable接口,并摆脱所有游戏对象的每个循环中的if语句:

if (gameObject instanceOf Touchable) { ... }

and just call gameObject.collision(p) and if it is not implemented by the subclass nothing will happened. 只需调用gameObject.collision(p) ,如果子类未实现它,则不会发生任何事情。 Do you think this is a better way? 您认为这是更好的方法吗?

I think it should still be part of the interface for the sake of code readability. 为了代码的可读性,我认为它应该仍然是接口的一部分。 It's much more obvious that way and you can also put any other methods that you discover later on to be constant throughout your program inside the same interface. 这样更明显,您还可以将以后发现的任何其他方法在整个程序中放在同一接口内保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM