我最近转向了 OOP 范式。我对其架构有一个紧迫的问题。我在网上到处搜索,结果却更加困惑。出于学习目的,我正在制作一个垄断游戏。我的架构如下:
export class Monopoly {
constructor() {
this.players = new PlayerContoller();
this.board = new Board();
this.dice = new Dice();
this.piece = new Piece();
}
然后在这些对象中我实例化了其他对象,例如 Property Utility Station、Square、Chance、Community chest 等。
我的问题是围绕玩家 Controller 的。需要吗?这就是它包含的内容
import { Player } from "./Player.js";
export class PlayersContoller {
constructor() {
this.players = [];
this.playerTurn = 0;
}
addPlayer(piece) {
const player = new Player(piece);
this.players.push(player);
}
getCurrentPlayer() {
return this.players[this.playerTurn];
}
changePlayersTurn() {
this.playerTurn++;
if (this.playerTurn === this.players.length) {// if the player reaches above the number of players its reset to 0
this.playerTurn = 0;
}
}
getAllPlayersObjects() {
return this.players;
}
}
这样做的目的是这样我不必将这些方法直接存储在主垄断类中,也不必将玩家数组存储在主垄断类中。我需要调用玩家本身的任何方法(例如increaseMoney())都存储在玩家类中,这些对象存储在玩家数组中,这是玩家 Controller 类的属性。 playerController 类只是控制轮到谁并找到当前玩家,这样我就可以从玩家类中调用它的方法,例如再次增加Money(),或者将数据传递到我的 View 中(我正在使用MVC模式)。
这些 Controller 类是否很常见,没有一个大的主类,或者我是否最好将数组作为属性存储在 Monopoly 类中并直接从 Monopoly 类调用方法?
最佳答案
我会将该类称为PlayerCircle
(甚至Table
)。其定义特征不仅在于它拥有一组玩家(您不需要额外的类),而且还在于它保留了轮到谁的状态。
鉴于此,我认为这是模型的一部分,而不是 Controller 。在经典 MVC 中, Controller 将 View 与模型连接起来,特别是与在模型上执行操作的方法连接起来。您的 PlayersController
不会执行此操作。
关于javascript - OOP 中 Controller 类常见吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73667756/