Global State and Singletons Dependency injection
dependency-injection, global-variables, singleton
Solution
That's why DI Containers manage lifecycle. Let the Playerlist be a singleton in terms of container lifecycle. Gives you full testability of components and let's the container (not you) get its hands dirty.
Problem
This is a problem I face a lot of times when I am designing a new app. I'll use a sample problem to explain this. I am writing simple game, so I want to hold a list of players. I have few options... - 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 - 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 - 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. I didn't actually solve anything. What is the optimum solution? (currently I use Singleton approach)