静态 class 用于模拟中的时间管理

Static class for time-management in simulation

我正在尝试使用 OOP(准确地说是 SC2)在 Java 中编写游戏模拟器。基本上游戏有单位(每个不同的单位是一个 class,每个实际创建的单位都是那个 class 的一个实例),并且有具有不同角色的建筑物。同样,每座建筑物都有自己的 class,并且在建造建筑物时,它的 class 会被实例化。所以我会有 u1, u2, u3, b1, b2 b3...等实例。

没问题。

现在,我需要模拟时间增量。我知道最终我需要用户能够与游戏互动(例如,在关键时刻,这取决于游戏并且在模拟之前不知道,我想要用户输入)。这意味着我希望游戏 运行 X 时间增量,然后可能会因特定事件停止(当获得 Y 资源时,允许创建 building/unit,或者当新建筑有已创建并开启了新的决策)。

总结一下我的(一般)classes:

class Unit extends GameElement{
  //bunch of attributes
  //bunch of units-specific methods, getters & not relevent here

   public void timeIncrement () {
     //Manages all time-dependant changes for this unit when
     //that method is called
    }
        }

与构建类似,他们将拥有自己的 timeIncrement 方法,这些方法将管理自己的(class-特定的)时间相关行为。

建筑物 classes 和单元 classes 都是以下项目的延伸:

abstract class GameElement {

//Manages time-dependant behaviours
public abstract void timeIncrement();

//Manages the building/creation of the game element
public abstract void building();
}

它定义了所需的常用方法,例如每个单元都必须管理它的时间和构建过程。

我有关于如何定义的问题

class TimeManagement{
    //Those ArrayList list all objects created with a 
    //timeIncrement() method that needs to be called
    private ArrayList<Units> = new ArrayList<Units>();
    private ArrayList<Buildings> = new ArrayList<Buildings>();
    //This is the (universal game-wide) timestep. It might change so I
    //need to have a single-place to edit it, e.g. global variable
    private double TIME_STEP = 0.5;

}

基本上我的计划是让 TimeManagement 和 ArrayList 包含它需要告知时间已经增加的所有对象。对于每个 arrayList,它将遍历它包含的对象并调用 myObject.timeIncrement() 方法,然后对象将管理他递增,但是它们被编程为。

我的问题是如何定义这个 TimeManagement class。实例化这个 class 对我来说没有意义。但是如果我声明它是静态的,我不能(除非我错了 - 我还没有使用静态 classes 很多)在我构建新单元时更新它的 ArrayList,那么 TimeManagement 将如何能够为所有需要它的对象调用 timeIncrement?

或者我是否应该只创建一个 TimeManagement 的虚假实例,这样我就不必将其声明为静态的?但从编程的角度来看,这感觉不对。

我更愿意使用这种通用架构来解决问题。在我看来,它需要类似于此 TimeManagement class 的内容,但我似乎无法完全理解它....

快捷方式

您可以简单地将所有字段设为静态:

class TimeManagement {
    private static List<Unit> = new ArrayList<Unit>();
    private static List<Building> = new ArrayList<Building>();

    private static final double TIME_STEP = 0.5;
}

这样,你需要一直静态引用TimeManagement

使用单例模式

但是,在这种情况下,我宁愿使用单例来代替:

class TimeManagement {
    private static final double TIME_STEP = 0.5;
    
    private List<Unit> = new ArrayList<Unit>();
    private List<Building> = new ArrayList<Building>();

    private TimeManagement instance;

    public static TimeManagement getInstance() {
        if (instance == null) {
            instance = new TimeManagement();
        }
        return instance;
    }
}

这样,您将通过调用 #getInstance() 方法获得一个现有实例。代码的进一步说明:我将 TIME_STEP 变量保持静态,至于常量,这是有道理的,因为它们固有地绑定到 class,而不是特定实例。