我正在尝试使用OOP(准确地说是SC2)用Java编写游戏模拟器。基本上,游戏有单元(每个不同的单元是一个类,每个实际创建的单元是该类的一个实例),并有不同角色的建筑。同样,每个建筑都有自己的类,当一个建筑被建造时,它的类被实例化。所以我会有u1,u2,u3,b1,b2b3…等等实例。
这一切都很好。
现在,我需要模拟时间增量。我知道,最终我需要用户能够与游戏互动(例如,在关键时刻,这取决于游戏,在模拟之前不知道,我需要用户输入)。这意味着我希望游戏运行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;
}
基本上,我的计划是使用带有ArrayList的TimeManagement来显示时间增加所需的所有对象。对于每个arrayList,它将循环遍历它所包含的对象,并调用myObject.timeIncrement()方法,然后对象将按照编程的方式管理增量。
我的问题是如何定义这个TimeManagement类。实例化这个类对我来说没有意义。但是,如果我声明它是静态的,我就不能(除非我错了——我还没有经常使用静态类)在构建新单元时更新它的ArrayList,那么TimeManagement如何能够为所有需要它的对象调用timeIncrement呢?
或者我应该只创建一个TimeManagement的伪实例,这样我就不必声明它为静态的吗?但从编程的角度来看,这感觉不对。
我更愿意用这个通用架构来解决一些问题。在我看来,这需要一些与时间管理课程类似的东西,但我只是无法完全理解。。。。
快速方法
您可以简单地将所有字段设置为静态:
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
。
使用Singleton模式
然而,在这种情况下,我宁愿使用singleton:
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
变量保持为静态,对于常量,这是有意义的,因为它们固有地绑定到类,而不是特定的实例。