EvgeniVT

Engine and CommandInterpreter

Nov 29th, 2019
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.37 KB | None | 0 0
  1. using CommandPattern.Core.Contracts;
  2. using System;
  3. using System.Linq;
  4. using System.Reflection;
  5.  
  6. namespace CommandPattern.Core
  7. {
  8.     public class Engine : IEngine
  9.     {
  10.         private readonly ICommandInterpreter commandInterpreter;
  11.         public Engine(ICommandInterpreter command)
  12.         {
  13.             this.commandInterpreter = command;
  14.         }
  15.         public void Run()
  16.         {
  17.             while (true)
  18.             {
  19.                 var input = Console.ReadLine();
  20.                 var result = this.commandInterpreter.Read(input);
  21.                 Console.WriteLine(result);
  22.             }
  23.         }
  24.     }
  25.     public class CommandInterpreter : ICommandInterpreter
  26.     {
  27.         public string Read(string args)
  28.         {
  29.             var data = args.Split(" ", StringSplitOptions.RemoveEmptyEntries);
  30.             var com = (data[0]+ "Command").ToLower();
  31.             var comArgs = data.Skip(1).ToArray();
  32.             var type = Assembly.GetCallingAssembly().GetTypes().FirstOrDefault(x => x.Name.ToLower() == com);
  33.             if (type == null) throw new ArgumentException("Invalid command type!");
  34.             var instance = Activator.CreateInstance(type) as ICommand;
  35.             if (instance == null) throw new ArgumentException("Invalid command type!");
  36.             var result = instance.Execute(comArgs);
  37.             return result;
  38.         }
  39.     }    
  40. }
Advertisement
Add Comment
Please, Sign In to add comment