开发者

Android/Java(?) - accessing parent from child

开发者 https://www.devze.com 2023-04-02 09:26 出处:网络
I am (trying to) making a simple boardgame. Its U开发者_如何学CI should be very simple, a top component representing a drawing of the board itself, and on the bottom, a few TextViews giving some relev

I am (trying to) making a simple boardgame. Its U开发者_如何学CI should be very simple, a top component representing a drawing of the board itself, and on the bottom, a few TextViews giving some relevant info (turns, number of tokens on the board, current player, ...).

I have an Activity, with:

  • A Game member, which handles all the logic.
  • A BoardView extending View, to draw the game board, which handles the interaction.
  • TextViews which should show some additional interaction.

So the BoardView and TextView instances need to access info from their sibling Game. How shall I access it?


You can either construct both classes BoardView and TextView with the same Game instance,

Game game = new Game();
BoardView board = new BoardView(game);
TextView text = new TextView(game);

or make Game a singleton which holds its own instance.

public class Game{

private Game game;
//private constructor
private Game(){};    

//synchronised method to create a game instance
private  synchronized static void createInstance () {
    if (game == null) game = new Game ();
}


public static void getInstance(){
  if(game==null){
    createInstance();
  }
  return game;
}

Then you can get the same game instance in both classes by calling

Game game = Game.getInstance();


Benjamin's answer from above is what you need. You can try MVC pattern with an implementation as suggested here

0

精彩评论

暂无评论...
验证码 换一张
取 消