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 TextView
s 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
extendingView
, to draw the game board, which handles the interaction. TextView
s 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
精彩评论