lundi 2 janvier 2023

Is passing context class attributes as parameters to a strategy method (when the strategy is itself a part of the context) correct?

I am implementing the Snakes and Ladders game. Where Game is one class which has Board, Dice, Players and 2 strategies - Winning Strategy and EndGameStrategy. Different implementations of EndGameStrategy can be -

  1. If one player wins, the game ends - OnePlayerWonGameEndStrategy
  2. If only 1 player remains at last, the game ends - OnlyOnePlayerLeftGameEndStrategy

The Game model looks as below:

@Builder
@Getter
public class Game {
    private Board board;
    private Queue<Player> players;
    private List<Dice> dices;
    private final int MAX_BOARD_SIZE = 1000;
    private final int MAX_NUMBER_OF_PLAYERS = 10;
    private final int MAX_NUMBER_OF_DICE = 5;
    private int totalPlayers;
    private GameEndStrategy gameEndStrategy;
    private WinningStrategy winningStrategy;
    private Queue<Player>leaderBoard;
}

The Client initializes strategies using builder.

Game game = Game.Builder()
                .setBoard(board)
                .setPlayers(playerList)
                .setDices(diceList)
                .setGameEndStrategy(new OnlyOnePlayerLeftGameEndStrategy())
                .build();

One of the implementation of GameEndStrategy is OnlyOneplayerLeftGameEndStrategy

public class OnlyOnePlayerLeftGameEndStrategy implements GameEndStrategy{
    @Override
    public Boolean isGameEnd(int activePlayers, int totalPlayers) {
        return activePlayers == 1;
    }
}

Other implementation is when the first player wins, the game ends

public class OnePlayerWonGameEndStrategy implements GameEndStrategy{
    @Override
    public Boolean isGameEnd(int activePlayers, int totalPlayers) {
        return totalPlayers - activePlayers == 1;
    }
}

The client uses the strategy as follows:

while(!game.getGameEndStrategy().isGameEnd(game.getPlayers().size(), game.getTotalPlayers())) {
    \\Game logic (Player throws dice, new position is checked
}

Here as parameters of isGameEnd method, should I pass the context class i.e the Game instance as the param? because, OnlyOnePlayerLeftGameEndStrategy would only need the activePlayers number to check if one one player is left. But, OnePlayerWonGameEndStartegy needs both totalPlayers and activePlayers as params to check if one player has won. Also there could be another strategy in future which would need more params. So how should we handle changing params? How should we implement the strategy pattern here in this Snakes and Ladders usecase?

Aucun commentaire:

Enregistrer un commentaire