Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Refactoring switch to Dictionary
using System;
using System.Collections.Generic;
using Model.Strategies;
using Model.Strategies.Minimax;
namespace Model
{
public class PlayerFactory
{
private ITwoPlayersGame TwoPlayersGame { get; set; }
private readonly IDictionary<PlayerType, Func<string, Player>> builders;
public PlayerFactory(ITwoPlayersGame twoPlayersGame)
{
TwoPlayersGame = twoPlayersGame;
builders = new Dictionary<PlayerType, Func<string, Player>>()
{
{PlayerType.ComputerDefault, CreateComputerPlayerDefault},
{PlayerType.ComputerMinimax, CreateComputerPlayerMinimax},
{PlayerType.ComputerRandom, CreateComputerPlayerRandom},
{PlayerType.Human, CreateHumanPlayer}
};
}
public Player CreatePlayer(string name, PlayerType type)
{
Func<string, Player> builder;
if (!builders.TryGetValue(type, out builder))
throw new ArgumentOutOfRangeException("type");
return builder(name);
}
private static Player CreateComputerPlayerDefault(string name)
{
return new ComputerPlayer(name);
}
private ComputerPlayer CreateComputerPlayerMinimax(string name)
{
var computer = new ComputerPlayer(name);
computer.Strategy = new MinimaxStrategy(TwoPlayersGame, computer);
return computer;
}
private ComputerPlayer CreateComputerPlayerRandom(string name)
{
var computer = new ComputerPlayer(name) {Strategy = new RandomStrategy()};
return computer;
}
private HumanPlayer CreateHumanPlayer(string name)
{
var human = new HumanPlayer(name);
return human;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.