Created
May 7, 2014 18:53
-
-
Save jmhdez/b9ad6f841ff9c8e87af5 to your computer and use it in GitHub Desktop.
Refactoring switch to Dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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