Global State and Singletons Dependency injection
- by Manu
this is a problem i face lot of times when i am designing a new app
i'll use a sample problem to explain this
think i am writing simple game.so i want to hold a list of players.
i have few options..
1.use a static field in some class
private static ArrayList<Player> players = new ArrayList<Integer>();
public Player getPlayer(int i){
return players.get(i);
}
but this a global state
2.or i can use a singleton
class PlayerList{
private PlayerList instance;
private PlayerList(){...}
public PlayerList getInstance() {
if(instance==null){
...
}
return instance;
}
}
but this is bad because it's a singleton
3.Dependency injection
class Game {
private PlayerList playerList;
public Game(PlayerList list) {
this.list = list;
}
public PlayerList getPlayerList() {
return playerList;
}
}
this seems good but it's not,
if any object outside Game need to look at PlayerList (which is the usual case)
i have to use one of the above methods to make the Game class available globally.
so I just add another layer to the problem. didn't actually solve anything.
what is the optimum solution ?
(currently i use Singleton approach)