避免复合模式中的instanceof [英] Avoid instanceof in a composite pattern

查看:125
本文介绍了避免复合模式中的instanceof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为大学设计一个游戏项目。在这个游戏中可以发生几种效果,一种效果可以影响另一种效果的行为。现在,其中一个想法是使用复合图案,起初看起来像是一个坚固的解决方案。这里最大的问题是效果表现的方式取决于它的效果,我们看到解决这个问题的唯一方法就是使用我们想要不惜一切代价避免使用的.getClass()或instanceof。

I'm working on a project for university where we're programming a game. In this game several effects can occur and one effect can affect how another effect behaves. Now one of the idea's was using a composite pattern which seemed like a solid solution at first. The biggest problem here is that the way an effect behaves depends on what effect it's coupled with and the only way we saw to fix this was using .getClass() or instanceof which we want to avoid at all cost.

有什么方法可以设计这个问题?

What are some ways to design this issue?

编辑(一个小例子):
我没有明确的代码示例,但我会尝试用以下示例澄清一下:

Edit (a small example): I don't have a explicit code example but I'll try to clarify a bit with the following example:

所以游戏中有手榴弹(显然会爆炸并造成伤害),这次爆炸是被视为爆炸效应。手榴弹所在的方形在运行时可能会出现电力故障(PowerfailureEffect)。 ExplosionEffect和PowerfailureEffect可以耦合,这会导致爆炸更强烈并造成更多伤害。 ExplosionEffect还可以与其他效果相结合,导致爆炸伤害的行为更加不同

So the game has grenades (which can obviously explode and cause damage), this explosion is seen as an "ExplosionEffect". The square that the grenade is positioned on can have a powerfailure at runtime (PowerfailureEffect). The ExplosionEffect and PowerfailureEffect can be coupled and this causes the explosion to be stronger and cause more damage. The ExplosionEffect can also be coupled with other effects causing the explosion damage to behave even more differently

推荐答案

您可以使用访客设计模式。
所有效果类都实现了一个Effect接口。
Main class使用Effect接口方法询问EffectB类应该如何表现。
EffectB类中Effect的方法的实现在主类中调用正确的方法。

You could use the Visitor Design Pattern. All effect class implements an Effect interface. Main class ask the EffectB class using the Effect interface method how it should behave. Implementation of Effect's method in EffectB class call the right method in main class.

这篇关于避免复合模式中的instanceof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆