Understanding strategy pattern by designing game of chess

Today we will try to understand Strategy Pattern with the help of an example.
The example we will consider is The Game of Chess. The intention here is to explain strategy pattern and not to build a comprehensive Chess Game solution.

Strategy Pattern : The Strategy pattern is known as a behavioural pattern – it’s used to manage algorithms, relationships and responsibilities between objects. The main benefit of strategy pattern is to choose the algorithm/behaviour at runtime.

StrategyPattern

Lets try to understand this by implementing this to design the chess game.

In chess there are different characters like King, Queen, Bishop and all of them have different moves. There could be many possible solutions to this design, lets explore one by one :

1) The first way would be to define movement in each and every class, every character will have its own move() implementation. In this way there is no code reusability and we can not change the implementation at run time.

2) Make a separate MovementController Class and put an if else for each type of movement of an object.

public class BadDesginCharacterMovementController {

    public void move(Character character){
        if(character instanceof King){
            System.out.print("Move One Step forward");
        }else if(character instanceof Queen){
            System.out.print("Move One Step forward");
        }else if(character instanceof Bishop){
            System.out.print("Move diagonally");
        }
    }
}

This is a poor design, with strong coupling, moreover using if/else makes it ugly.

So, we would like to have a design where we can have loose coupling, where we can decide the movement algorithm at run time and there is code reusability.

Lets see this complete implementation using Strategy Pattern.

Below is that class diagram of our implementation:

Chess

The complete source code can be downloaded from here.

We will have our base abstract class as Character Class, which all the characters can extend and set their own MovementBehaviour implementation.

public class Character {

    private MovementBehaviour movementBehaviour;

    String move(){
       return movementBehaviour.move();
    }

    public void setMovementBehaviour(MovementBehaviour movementBehaviour) {
        this.movementBehaviour = movementBehaviour;
    }
}

This class has a movement Behaviour:

public interface MovementBehaviour {

    String move();
}

So, each Character : King,Queen,Bishop will extend Character and they can have their own implementation of Movement Behaviour.

public class King extends Character {

    public King() {
        setMovementBehaviour(new SingleForward());
    }
}

Here for simplicity, I have called the setMovemementBehaviour method inside the constructor of King.

Similarly, another character Queen can be defined as :

public class Queen extends Character {

    public Queen() {
        setMovementBehaviour(new SingleForward());
    }
}

And, Bishop as :

public class Bishop extends Character {

    public Bishop() {
        setMovementBehaviour(new DiagonalMovement());
    }
}

The implementation of different movements can be as follows:

Single Forward :

public class SingleForward implements MovementBehaviour {

    @Override
    public String move() {
       return "move one step forward";
    }
}

Diagonal Movement:

public class DiagonalMovement implements MovementBehaviour {

    @Override
    public String move() {
        return "Moving Diagonally";
    }
}

With this example we can understand the Strategy Pattern.

Advertisements

4 thoughts on “Understanding strategy pattern by designing game of chess

  1. Hi!
    What if every character has different move strategy? Would it be good then if everyone implement just move() method from upper class/interface? I mean: would we then use simple inheritance over the strategy pattern? What would be better?

    PS. I could not post on JCG, I had problems with captcha.

    • If every Character had their own implementation of move() then yes inheritance could be fine. But if there is a case, where a character does not move (hypothetical, like the wooden duck example which can not fly, stated in Head First DP); even then this character will have to implement move with something like ( “Action not supported Exception” ).

      The main benefit of Strategy pattern is in being able to switch out different implementations for different situations. Hope it helps.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s