我想创建一个简单的游戏并使用一个 IoC 容器。每个游戏都有玩家,所以我想将他们注入(inject) Game
类(class)。问题是,可能有不同类型的玩家。第一个玩家将始终是人类(设备所有者;)),但他的对手:人类(游戏和传球)、机器人或在线(人类,但通过互联网游戏)。
这是代码。有不同的玩家:
public class Human : IPlayer
{
public int Id { get; set; }
public string Name { get; set; }
public PlayerType Type { get; set; }
}
public class Bot : Human
{
}
public class OnlinePlayer : Human
{
}
public interface IPlayer
{
int Id { get; set; }
string Name { get; set; }
PlayerType Type { get; set; }
}
和Game
类:
public class Game : IGame
{
public GameType Type { get; private set; }
public List<IPlayer> Players { get; private set; }
public Game(GameType type, List<IPlayer> players)
{
Type = type;
Players = players;
}
}
public interface IGame
{
GameType Type { get; }
List<IPlayer> Players { get; }
}
如您所见,我在 Game 的容器中注入(inject)了玩家列表。这是我的问题:
如何解决 List<IPlayer>
如果类型不同 GameType
?
如果 GameType = 单人游戏 -> 注入(inject)人类和机器人
if GameType = Pass and play -> Inject Human and Human
if GameType = Online game -> Inject Human and OnlinePlayer
最佳答案
没有理由让它变得比它必须的更复杂。你可以放这样的东西 in an Abstract Factory :
if (gameType == GameType.Single)
return new Game(
GameType.Single,
new List<IPlayer> { CreateHuman(); CreateBot() });
else if (gameType == GameType.PassAndPlay)
return new Game(
GameType.PassAndPlay,
new List<IPlayer> { CreateHuman(); CreateHuman() });
else
return new Game(
GameType.Online,
new List<IPlayer> { CreateHuman(); CreateOnlinePlayer() });
关于C# 国际奥委会 : Implementing conditional injection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33586245/