As for many patterns, the Strategy Pattern improves cohesion by removing
if
statements in code. In this lab, you will refactor your Lab 1
solution to remove the if statements based on whether a piece is regular or
a king. You may leave the if statements based on whether a piece is red or
black, but if you prefer you can use the Strategy Pattern to remove those
as well.
Note that this lab talks about if
statements for simplicity. What is
really meant is any sort of conditional. This includes switch
and the ?
operator (such as x = p ? a : b
). Replacing an if
by another
conditional does not meet the goals of the lab.
Fix any issues noted by your instructor in your previous lab’s submission.
Create an interface or abstract class for MoveBehavior
. It must have isValidOrdinaryMove
and getCapturedPiece
methods in it. Having a class with the name Behavior in it makes it obvious to other developers that you are using the Strategy Pattern (since that pattern is tied closely to varying behaviors).
Create classes derived from MoveBehavior
. These will reflect the different ways to move pieces (such as red vs. black and king vs. regular piece). You will implement the behaviors below; write skeleton classes for now.
Introduce a MoveBehavior
member in Piece
. This member must be updated when a regular piece becomes a king.
Design and implement the behavior classes you introduced. This includes determining how they will access the piece they control, determining each method’s arguments and return values, and deciding if you need to add getter methods for any private data. Sketching a class or sequence diagram may improve your design.
Eliminate control coupling and logical cohesion from the isValidOrdinaryMove
and getCapturedPiece
methods. That is, these methods should have no if statements based on whether the piece represents a king. If you also write behaviors based on red vs. black pieces, the if statements based on color will also be removed, but otherwise conditionals based on red/black will remain.
Please see your instructor’s guidance on submitting this lab. This includes meeting your instructor’s coding standard and creating any required UML diagrams.