lundi 24 mai 2021

Java Decorator Pattern

I'm trying to implement the Java decorator pattern in my project. Basically the project has two sets of warriors (aggressive and defensive) and I created an abstract warrior class that is the parent to the two different types of warriors. Aggressive warriors and defensive warriors have their attack, defense, and boost fields calculated differently. I have created a decorator class that manipulates the getDefense() method where I just get the double of the defense. Now I'm supposed to calculate the attack, defense, boost, and power of this decorated warrior class. I was able to pass most of the test but the tricky part came when I was supposed to calculate the attack, defense, and boost twice with different return values. For example defensive warrior calculates defense by adding the defense to (2*level) but aggressive warrior does the same by just adding the defense + level. This is where I run into trouble because I'm not sure how to use the same method twice with two different calculations.

public class ArmoredWarriorDecorator extends Warrior {

    Warrior warrior;

    public ArmoredWarriorDecorator(Warrior warrior) {
        super(warrior);
        this.warrior = warrior;
    }

    @Override
    int getDefense() {
        int defense = (int) (2 * warrior.defense);
        return defense;
    }

    @Override
    public int calculateAttack() {
        return (int) warrior.attack + warrior.level;
    }

    @Override
    public int calculateDefense() {
        return (int) (warrior.defense * 2 + (2 * warrior.level));
    }

    /*
     * @Override public int calculateDefense() { return (int) (warrior.defense * 2 +
     * (warrior.level)); }
     */

    @Override
    public double calculateBoost() {
        return warrior.defense;
    }

}
@Test
void double_defense_calculate_defense_defensive() {
    Warrior warrior = new ArmoredWarriorDecorator(new DefensiveWarrior.Builder(1).defense(10).build());
    assertSame(22, warrior.calculateDefense());
}

@Test
void double_defense_calculate_defense_aggressive() {
    Warrior warrior = new ArmoredWarriorDecorator(new AggressiveWarrior.Builder(1).defense(10).build());
    assertSame(21, warrior.calculateDefense());
}

Aucun commentaire:

Enregistrer un commentaire