模拟中时间管理的静态类

时间:2015-02-23 16:28:13

标签: java static-classes

我试图使用OOP(精确的SC2)用Java编写游戏模拟器。基本上游戏有单位(每个不同的单位是一个类,每个实际创建的单位是该类的一个实例),并且具有不同角色的建筑物。每个建筑物都有自己的类,当构建建筑物时,它的类被实例化。所以我会有u1,u2,u3,b1,b2 b3 ......等实例。

一切都很好。

现在,我需要模拟时间增量。我知道最终我需要用户能够与游戏进行交互(例如,在关键时刻,这取决于游戏,在模拟之前不知道,我想要用户输入)。这意味着我希望游戏以X时间为增量运行,然后可能为特定事件停止(当获得Y资源时,可以创建建筑物/单元,或者创建新建筑物并开启新决定)。

所以总结一下这是我的(普通)课程:

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方法,这些方法将管理自己的(特定于类)时间依赖的行为。

两个建筑类和单元类是以下的扩展:

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类。对我实例化这个类没有意义。但是,如果我声明它是静态的我不能(除非我错了 - 我还没有使用静态类)当我构建新单元时更新它的ArrayList,那么TimeManagement将如何?能够为所有需要它的对象调用timeIncrement吗?

或者我应该创建一个TimeManagement的虚假实例,所以我不必将其声明为静态?但从编程的角度来看,这只是错误的。

我更愿意使用这种通用架构来解决问题。在我看来,它需要这个时间管理课程的一些东西,但我似乎不能完全把它放在它上面......

1 个答案:

答案 0 :(得分:1)

快捷方式

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

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变量保持为静态,对于常量,它是有意义的,因为它们固有地绑定到类,而不是特定的实例。