Java - 将类实例附加到另一个类实例

时间:2016-04-19 11:51:56

标签: java class

尝试使用预配置的实例创建二十一点游戏(需要使用提供的方法签名)。我有一个testHarness / client类,它贯穿游戏循环。客户端类有:

final GameEngine gameEngine = new GameEngineImpl();

所以gameEngine是GameEngineImpl的新实例。

然后客户端有一个方法将GameEngineCallbackImpl的实例附加到gameEngine。

gameEngine.addGameEngineCallback(new GameEngineCallbackImpl());

GameEngineImpl中addGameEngineCallback的方法签名如下所示

public void addGameEngineCallback(GameEngineCallback gameEngineCallback)

所以GameEngineCallback gameEngineCallback = new GameEngineCallbackImpl()???

如何将gameEngineCallback附加到gameEngine?我可以通过参考吗?喜欢这个?

public void addGameEngineCallback(GameEngineCallback gameEngineCallback) {
  GameEngineCallback gameEngineCallbackCurrent = null;
  gameEngineCallback = gameEngineCallbackCurrent;

}

1 个答案:

答案 0 :(得分:0)

将一个对象(“附加”)“附加”到另一个(“容器”)的方法是在附件中保持对作为instance variable的附件的引用:

public class GameEngine {
  // an instance variable, declared outside of the methods.
  // its lifetime equals that of the game engine instance
  private GameEngineCallback gameEngineCallback;

  public void addGameEngineCallback(GameEngineCallback gameEngineCallback) {
    this.gameEngineCallback = gameEngineCallback;
  }

  // later on, the engine can call upon the callback to do stuff
  public void startGame() {
    this.gameEngineCallback.start();
  }
}