9

这是我在设计新应用程序时经常遇到的问题。我将使用一个示例问题来解释这一点。

我正在写简单的游戏,所以我想保存一个玩家列表。我有几个选择...

  1. 在某个类中使用静态字段
private  static ArrayList<Player> players = new ArrayList<Integer>();  
public Player getPlayer(int i){
    return players.get(i);
}

但这是一个全球状态

  1. 或者我可以使用单例
class PlayerList{
    private PlayerList instance;
    private PlayerList(){...}
    public PlayerList getInstance() {
        if(instance==null){
            ...
        }
        return instance;
    } 
 }

但这很糟糕,因为它是单例

  1. 依赖注入
class Game {
    private PlayerList playerList;
    public Game(PlayerList list) {
        this.list = list;
    }
    public PlayerList getPlayerList() {
        return playerList;
    }
}

这看起来不错,但事实并非如此。

如果需要查看 Game 之外的任何对象PlayerList(这是通常的情况) ,我必须使用上述方法之一来使 Game 类全局可用。所以我只是为问题添加了另一层。我实际上并没有解决任何问题。

最佳解决方案是什么?(目前我使用单例方法)

4

3 回答 3

4

这就是 DI 容器管理生命周期的原因。就容器生命周期而言,让 Playerlist 成为单例。为您提供组件的完整可测试性,让容器(而不是您)亲自动手。

于 2009-09-01T20:19:42.760 回答
2

The idea behind dependency injection is as the name states to inject dependencies. So whatever object needs to know about the player list will be injected with it. Usually, it makes a lot of sense to use dependency injection as extensively as possible before switching to dependency lookup or some other mechanism. This will also make it possible to extend the game later to have different player lists for different levels or whatever extension you might think about.

于 2009-09-01T19:42:36.067 回答
1

If you need PlayerList outside of Game, maybe Game is the wrong class for this? If any other object needs PlayerList, either they need to have the List injected as well, or maybe you should move the list to this class instead of the Game class.

If you have different lifetimes for Game, PlayerList and other Classes, maybe also consider using a Factory to group them. Check this Google Testing Blog article for details.

于 2009-09-01T19:50:15.863 回答