Avoid Instance in Compound Template

I am working on a project for a university where we program a game. Several effects may occur in this game, and one effect may affect the behavior of another effect. Now one of the ideas was to use a complex template, which at first seemed like a solid decision. The biggest problem is that the way the effect affects depends on which effect it is associated with, and the only way we saw to fix it was using .getClass () or instanceof, which we want to avoid any at the price.

What are some ways to solve this problem?

Edit (small example): I do not have an explicit code example, but I will try to clarify the following example a bit:

So, in the game there are grenades (which, obviously, can explode and cause damage), this explosion is considered as "ExplosionEffect". The square where the grenade is located may have power failures at runtime (PowerfailureEffect). The effect of ExplosionEffect and PowerfailureEffect can be connected, and this leads to the fact that the explosion becomes stronger and does more damage. The ExplosionEffect effect can also be associated with other effects that cause the explosion damage to behave even more differently.

+5
source share
4 answers

. Effect. EffectB, Effect, . Effect EffectB .

+2

. , Modifier, . , "IncreaseExplosivePower". instanceof, , , .

. instanceof - , - , , , API- .

+1
public void test(){
    methodForWaterEffect(new WaterEffect());
    combinationAttack1(new FireEffect(), new WaterEffect());
}

interface Effect{
    public void activateEffect();
}

class FireEffect implements Effect{

    @Override
    public void activateEffect() {
        System.out.println("Fire!");
    }

}

class WaterEffect implements Effect{

    @Override
    public void activateEffect() {
        System.out.println("Water!");
    }

}
public void combinationAttack1(FireEffect fe, WaterEffect we){
    //your algorithm here

}

public void methodForWaterEffect(WaterEffect fe){
    fe.activateEffect();
}

. , "". , , ?

,

public void combination2(PoisonEffect pe, PowerFailureEffect pf){

}

, , , .

, = D.

0

- , , instanceof . .

public class Shape {
    public void draw() {
        if (this instanceof Square) {
            // Draw a square
        } else if (this instanceof Circle) {
            // Draw a circle
        }
    }
}

public class Square extends Shape {
    // ...
}

public class Circle extends Shape {
    // ...
}

, draw() Shape , , . : class Shape , , Shape. , draw() :

public abstract class Shape {
    public abstract void draw();
}

public class Square extends Shape {
    public void draw() {
        // Draw a square
    }
}

public class Circle extends Shape {
    public void draw() {
        // Draw a circle
    }
}

, Shape , Shape, , , , , ( ).

-1

All Articles