Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid instanceof in a composite pattern

Tags:

java

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:

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

like image 981
user757926 Avatar asked Nov 02 '22 23:11

user757926


1 Answers

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.

like image 82
DeadlyJesus Avatar answered Nov 11 '22 17:11

DeadlyJesus