同步类

时间:2015-11-21 09:13:45

标签: java class variables synchronized

对于其中一个Java作业,我必须制作Breakout。即使在将程序拆分为类之后,这仍然有效,但是存在一个问题:需要将一些实例变量从主类传递给子类(即在主类的init()中我定义了一个实例子类中的变量具有与主类中的实例变量相同的值)。我提出了一个解决方案:只需要一个包含所有实例变量的类,但这会产生一个问题:许多实例变量都是非最终的,但是如果我这样做,那么更改CURRENT_SCORE变量主类,另一个类看到的值将保持不变。有没有办法让我对一个类中的变量类所做的所有更改对其他类都成立?

编辑: 我意识到我对'子类'一词的使用可能有点令人困惑,所以这里有一些示例代码来澄清我的意思:

public class Breakout extends GraphicsProgram{

// ---- IMPORTS ---- //

// instance variables
public BreakoutVariables INST_VARS;

// booleans
public BreakoutBooleans BOOLEANS;

// importing the bricks
public BreakoutBricks BRICKS;

// importing the counters
public BreakoutDisplay DISPLAY;

// ----- IMPORTS ----- //

public void init(){
    Import();

}

// imports all classes and sets their variables
private void Import(){
    INST_VARS = new BreakoutVariables();
    INST_VARS.InitGameWindow();
    BOOLEANS = new BreakoutBooleans();
    BRICKS = new BreakoutBricks();
    DISPLAY = new BreakoutDisplay();
}


// ----- BASE ----- PROGRAMS ----- //
// etc.

变量类:

public class BreakoutVariables extends GraphicsProgram{

// width and height of application window in pixels
public static final int APPLICATION_WIDTH = 500;
public static final int APPLICATION_HEIGHT = 400;

public GCanvas GAME_WINDOW = new GCanvas();

static {
    GAME_WINDOW.setSize(APPLICATION_WIDTH, APPLICATION_HEIGHT);
}

public void InitGameWindow(){

}

// ----- GENERAL ----- SETTINGS ----- //



// dimensions of game board (usually the same)
public static final int WIDTH = APPLICATION_WIDTH;
public static final int HEIGHT = APPLICATION_HEIGHT;

// animation delay or pause time between ball moves
public static final int DELAY = 5;

// manual game stopper
public int FORCE_STOP = 0;

// real timer (in miliseconds)
public int M_TIME = 0;
etc.

编辑2:

以下是问题出现的第一点:GAME_WINDOW变量。在BreakoutVariables()中定义GCanvas后,我尝试在BreakoutDisplay()类中添加背景,我得到一个空异常,因为Java告诉我GAME_WINDOW尚未定义。

BreakoutDisplay()中的代码:

// draws the background
public void DrawBackground(){
    INST_VARS.BACKGROUND.setFilled(true);
    INST_VARS.BACKGROUND.setFillColor(INST_VARS.BACKGROUND_COLOR);
    INST_VARS.GAME_WINDOW.add(INST_VARS.BACKGROUND);
}

BACKGROUND是BreakoutVariables()中定义的GRect,INST_VARS是BreakoutVariables()的引用链接。

1 个答案:

答案 0 :(得分:0)

您不需要跨类同步访问 - 您需要跨线程同步访问,只要您只有一个线程,就不需要做任何事情。

另外,我建议上课GameState,其中包含游戏的当前状态;你可以传播它。

相关问题