gpt4 book ai didi

java - 观察者设计模式,我是不是搞反了?

转载 作者:行者123 更新时间:2023-12-01 12:13:28 26 4
gpt4 key购买 nike

我所在的类(class)正在实现大富翁游戏模拟,非常简单,只需将每次回合的结果打印到控制台供用户查看,最终我们会将其移动到 GUI,但现在我们只是S.o.P 到控制台每个玩家的回合结果。

这些结果是从 Player 类打印的。玩家类基本上将打印所需的所有信息保存在一个位置(即,playerName、rollTotal、origSquareLocation、newSquareLocation)。

我正在尝试围绕观察者设计模式进行思考,并使 MonopolyGame 类成为观察者,让 Player 类成为可观察者。这是可能的还是因为 MonopolyGame 类正在构建玩家而将其倒退?我需要创建一个单独的 GameObserver 类才能完成这项工作吗?

这是我的 MonopolyGame 类:

public class MonopolyGame {

private static final int ROUNDS_TOTAL = 40;
private static final int PLAYERS_TOTAL = 2;
private List<Player> players = new ArrayList<Player>(PLAYERS_TOTAL);
private Board board = new Board();
private Die[] dice = { new Die(), new Die() };

/**
* Default Constructor
*/
public MonopolyGame() {

Player p = new Player("Horse", dice, board);
players.add(p);
p = new Player("Car", dice, board);
players.add(p);
}

/**
* Method: playGame()
*
* starts a new MonopolyGame for the assigned amount of rounds.
*/
public void playGame() {

for (int i = 0; i < ROUNDS_TOTAL; i++) {
playRound();
}
}

/**
* Method: playRound()
*
* allows each player by iterator to take their turn for each round played.
*/
public void playRound() {
for (Iterator<Player> iter = players.iterator(); iter.hasNext(); ) {
Player player = iter.next();
player.takeTurn();
}
}

} // End MonopolyGame Class

这是我的玩家类别:

public class Player {

private String name;
private Piece piece;
private Board board;
private Die[] dice;

public Player(String name, Die[] dice, Board board) {
this.name = name;
this.dice = dice;
this.board = board;
this.piece = new Piece(board.getStartSquare());
}

public void takeTurn() {

// Roll the dice
int rollTotal = 0;
for (int i = 0; i < dice.length; i++) {
dice[i].roll();
rollTotal += dice[i].getFaceValue();
}

// place the Players piece in the correct location.
Square newLoc = board.getSquare(piece.getLocation(), rollTotal);
piece.setLocation(newLoc);

System.out.println(getName() + " has rolled a " + rollTotal + " and landed on " + getLocation().getName());
}

public Square getLocation() {
return piece.getLocation();
}

public String getName() {
return name;
}

} // End Player Class

最佳答案

当然这是该模式的可能用途。但更自然地(至少对我来说)该模式的用法是像“ConsolePrinter”或“GuiBoardWindow”作为观察者,而游戏(或玩家)作为可观察者。由于观察者模式的主要思想是解耦不直接相关的部分。游戏的状态和玩家对象对我来说非常重要,以至于您可能不想将它们解耦。至少只要相邻的玩家或游戏不是游戏机制的实际模型/实体之外的任何东西。

关于java - 观察者设计模式,我是不是搞反了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27139464/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com