mercredi 2 décembre 2020

Java: 2 Decorators on 1 object with same method overrided

I'm working with decorator pattern in java and I encountered a problem. I have 2 decorators which override same method and I want them on the same object to do 2 implementations at once.

The first thing that comes to my mind is just combining two decorators to new one, but it is probably pretty bad idea in the long run.

What is the proper way of solving this issue? Do I need to go further more abstract or just reject decorators and use something else? (like strategy?)

Code example to visualize the problem:

public class Attacker {

//variables, constructor...


     public void attack(Object defender) {
       defender.hp -= 10;
    }

//other methods
}
public class HealAfterAttackDecorator extends Attacker {

//variables, consturctor...

     @Override
     public void attack(Object defender) {
        defender -= 10;
        this.heal();
     }
//other overrided methods
}
public class StunDefenderAfterAttackDecorator extends Attacker {
//variables, consturctor...

@Override
public void attack(Object defender) {
defender -= 10;
attack.stun(defender);

}
//other overrided methods
}

How to combine stun and healing into one?

Aucun commentaire:

Enregistrer un commentaire