Reputation: 85
This is more of a question where I'm trying to see if my thinking is correct before I start coding something that winds up not working. Let me see if I can explain what I'm trying to do first. My main issue is wanting to know if I'm on the right track or not.
I'm creating a game using the page viewer and fragments so I can have a tabbed layout. That's not a problem. Where I'm getting confused and turned around is that I have multiple activities, each handling a different part of the game so that I avoid having too much on the screen at any one time. I had wanted to have all of the game methods in a single class and have each activity pull from it. Can I do so if the class is private? I assume if I had a GAME class for example that I would have to instantiate a particular version of it somewhere but if I did, how can I be sure that everything is pulling from that same instance?
Another approach I had thought of was basically just making one game class that did everything and then just spit out the variable values to the various activities as needed which would then update the UI. Would that be a better approach? I think if I do it this way I can avoid having to pass data directly from one activity to the next. I can just have them all pull whatever values they need directly from the class.
Does any of this make any sense or am I way out in left field somewhere? Any direction to go in to start would be helpful as I've been going around for days trying to chart some kind of course.
Upvotes: 0
Views: 545
Reputation: 5940
It sounds like you want to put all your game logic into a Game class and have all of your Activities access that single Game instance. The answer is yes, that's probably the right approach and a simpler approach then trying to get your Activities to pass data around via Intents.
You can use a singleton pattern to get access to the same instance everywhere. (Something like this)
public class Game {
private static final Game INSTANCE = new Game();
private Game() {}
public static Game getInstance() {
return INSTANCE;
}
}
Or if you're using a dependency injection framework like Dagger, you can just mark the Game provider as providing a singleton. (If you don't know what this is, just use the singleton pattern above for now)
Upvotes: 1