javascript - OOP 中 Controller 类常见吗

标签 javascript class oop model-view-controller design-patterns

我最近转向了 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/

相关文章:

javascript - 有没有办法让数组中的单个项目识别包含其自身的同一数组对象?

javascript - 在图表标签中显示计算的百分比

r 如何保留自定义类的打印方法

javascript - OOP javascript 尝试访问方法

python - 如何修复Python类中的属性错误

javascript - 定位元素/div 的下一个实例

C++ 2D Vector 在 vector 中设置一个位置

javascript - 你如何在 JavaScript 中创建类?

ios - 从 Parent/Base 到 Child 类的 Swift Type Cast

javascript - 在 php 文件中执行 Google Chart API (Javascript)