interface实现polymopherson
View Code
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using TryCollection.Abstract; 6 7 namespace TryCollection 8 { 9 class Engine 10 { 11 private IState _state; 12 public IState State 13 { 14 get { return _state; } 15 set { _state = value; } 16 } 17 public void Run(IState initialState) 18 { 19 _state = initialState; 20 while (true) 21 { 22 _state.Render(); 23 var command = _state.GetCommand(); 24 command.Execute(); 25 } 26 } 27 } 28 }
dictionary实现key与value的配对
View Code
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using TryCollection.Abstract; 6 using System.Collections; 7 using TryCollection.States; 8 using TryCollection.Commands; 9 using TryCollection; 10 11 namespace TryCollection.States 12 { 13 class MainMenuState : IState 14 { 15 private Engine _engine; 16 private Dictionary<string, IState> _menuDictionary; 17 private ICommand _continueCommand; 18 private ICommand _helpCommand; 19 private IState _continueMenu; 20 private IState _helpMenu; 21 public MainMenuState(Engine engine) 22 { 23 _engine = engine; 24 _continueMenu = new ContinueMenu(_engine, this); 25 _helpMenu = this; 26 27 _menuDictionary = new Dictionary<string, IState> //制作dictionary,使输入与对应的menu匹配 28 { 29 { "con", _continueMenu }, 30 { "help", _helpMenu } 31 }; 32 } 33 34 public void Render() 35 { 36 37 Console.WriteLine("[con] - Continue"); 38 Console.WriteLine("[Help] - Help\n"); 39 } 40 41 public ICommand GetCommand() 42 { 43 var inputString = Console.ReadLine(); 44 // 45 foreach (var commandMenuPair in _menuDictionary) 46 { 47 if (commandMenuPair.Key == inputString) //这是Dictionary用的最巧妙的地方,不需要很多if else判断 48 { 49 _engine.State = commandMenuPair.Value; 50 ICommand command = ConvertCommand(inputString); 51 return command; 52 } 53 } 54 return new InvalidCommand(); 55 } 56 ICommand ConvertCommand(string commandString) 57 { 58 if (commandString == "con") 59 { 60 return new ContinueCommand(); 61 } 62 else 63 { 64 return new HelpCommand(); 65 } 66 } 67 68 69 } 70 }
Dictionary与IDictionary的区别。IDictionary例子:public IDictionary IMan<IShawn,IChris>, IShawn:IMan IChris:IMan,他们有同样的Iman方法