I am (trying to) making a simple boardgame. Its UI 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:
Game
member, which handles all the logic. BoardView
extending View
, 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.