Created
April 27, 2012 03:20
-
-
Save nelsonlaquet/2505420 to your computer and use it in GitHub Desktop.
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 System.Linq; | |
using System.Text; | |
namespace ConsoleApplication2 | |
{ | |
interface IState | |
{ | |
void Render(); | |
ICommand GetCommand(); | |
} | |
interface ICommand | |
{ | |
void Execute(); | |
} | |
class StateManager | |
{ | |
private IState _state; | |
public void SwitchState(IState state) | |
{ | |
_state = state; | |
} | |
public void Run(IState initialState) | |
{ | |
_state = initialState; | |
while (true) | |
{ | |
_state.Render(); | |
var command = _state.GetCommand(); | |
command.Execute(); | |
} | |
} | |
} | |
class SwitchStateCommand : ICommand | |
{ | |
private StateManager _manager; | |
private IState _newState; | |
public SwitchStateCommand(StateManager manager, IState newState) | |
{ | |
_manager = manager; | |
_newState = newState; | |
} | |
public void Execute() | |
{ | |
_manager.SwitchState(_newState); | |
} | |
} | |
class LoadState : IState | |
{ | |
public void Render() | |
{ | |
Console.WriteLine("Load a file"); | |
} | |
public ICommand GetCommand() | |
{ | |
Console.ReadLine(); | |
return null; | |
} | |
} | |
class HelpCommand : ICommand | |
{ | |
public void Execute() | |
{ | |
Console.WriteLine("HELP!"); | |
} | |
} | |
class InvalidCommand : ICommand | |
{ | |
public void Execute() | |
{ | |
Console.WriteLine("Invalid command"); | |
} | |
} | |
class MainMenuState : IState | |
{ | |
private StateManager _manager; | |
public MainMenuState(StateManager manager) | |
{ | |
_manager = manager; | |
} | |
public void Render() | |
{ | |
Console.WriteLine("[load] - load game"); | |
Console.WriteLine("[help] - show help"); | |
} | |
public ICommand GetCommand() | |
{ | |
var command = Console.ReadLine(); | |
if (command == "load") | |
{ | |
return new SwitchStateCommand(_manager, new LoadState()); | |
} | |
if (command == "help") | |
{ | |
return new HelpCommand(); | |
} | |
return new InvalidCommand(); | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var manager = new StateManager(); | |
manager.Run(new MainMenuState(manager)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment