Global State and Singletons Dependency injection

Posted by Manu on Stack Overflow See other posts from Stack Overflow or by Manu
Published on 2009-09-01T19:29:29Z Indexed on 2010/04/16 15:53 UTC
Read the original article Hit count: 153

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)

© Stack Overflow or respective owner

Related posts about singleton

Related posts about dependency-injection