Skip to content

Instantly share code, notes, and snippets.

@jmhdez
Created May 7, 2014 18:53
Show Gist options
  • Save jmhdez/b9ad6f841ff9c8e87af5 to your computer and use it in GitHub Desktop.
Save jmhdez/b9ad6f841ff9c8e87af5 to your computer and use it in GitHub Desktop.
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