Pattern

Pros

  • Class behavior can be changed at run time
  • Improves reusability by isolating behavior into their own class.
  • Eliminates conditional statements

Cons

  • Increases complexity
  • The client must know about strategies to pick which is best to use

Example Explanation

Mob - An abstract class which contains attackBehavior and moveBehavior through composition. The set behavior methods allow the class to change its behavior at anytime.

Zombie - Extends the abstract class Mob

IAttackBehavior - interface which forces each attack to implement the performAttack method

interface IAttackBehavior{
  public String performAttack();
}
interface IMovementBehavior{
  public String performMovement();
}

abstract class Mob {
  IAttackBehavior attack;
  IMovementBehavior move;
  String mobName;

  public Mob(IAttackBehavior attack, IMovementBehavior move){
    this.attack = attack;
  }

  public void executeAttack(){
    System.out.println(mobName+" "+attack.performAttack());
  }
  public void executeMovement(){
    System.out.println(mobName+" "+move.performMovement());
  }
  public void display(){
    System.out.println(mobName+" ["+attack.performAttack()+", "+move.performMovement()+"]");
  }
  public void setAttackBehavior(IAttackBehavior attack){ this.attack = attack; }
  public void setMoveBehavior(IMovementBehavior move){ this.move = move; }
}

class Zombie extends Mob{

  public Zombie(IAttackBehavior attack, IMovementBehavior move){
    super(attack, move);
    this.mobName = "Zombie";
    this.move = new WalkMovement();

  }
}

class SlashAttack implements IAttackBehavior{
  public String performAttack(){
    return "slashes";
  }
}
class BashAttack implements IAttackBehavior{
  public String performAttack(){
    return "bashes";
  }
}
class BiteAttack implements IAttackBehavior{
  public String performAttack(){
    return "bites";
  }
}

class WalkMovement implements IMovementBehavior{
  public String performMovement(){
    return "walks";
  }
}
class RunMovement implements IMovementBehavior{
  public String performMovement(){
    return "runs";
  }
}


class Main {
  public static void main(String[] args) {
    Mob monster = new Zombie(new BiteAttack(), new WalkMovement());
    monster.display(); //Zombie [bites, walks]
    monster.executeAttack(); //Zombie bites

    monster.setAttackBehavior(new BashAttack());
    monster.setMoveBehavior(new RunMovement());
    monster.display(); //Zombie [bashes, runs]

    monster.executeAttack(); //Zombie bashes
    monster.executeMovement(); //Zombie runs

    monster.setAttackBehavior(new SlashAttack());
    monster.display(); //Zombie [slashes, runs]
    monster.executeAttack(); //Zombie slashes

  }
}

Extra Resources

results matching ""

    No results matching ""