Skip to content

Instantly share code, notes, and snippets.

@fesenpav
Last active February 6, 2023 03:23
Show Gist options
  • Save fesenpav/9c8f3ac6545012cd3f7b80692c6c68b4 to your computer and use it in GitHub Desktop.
Save fesenpav/9c8f3ac6545012cd3f7b80692c6c68b4 to your computer and use it in GitHub Desktop.
Command Pattern in C#
// ICommand interface to extend the commands from
interface ICommand
{
void ExecuteCommand();
}
// First command
class HelloCommand : ICommand
{
public void ExecuteCommand()
{
// TODO: Some awesome command stuff here
}
}
// Second command
class ExitCommand : ICommand
{
public void ExecuteCommand()
{
// TODO: Some awesome command stuff here
}
}
class Program
{
static void Main(string[] args)
{
// Create dictionary for commands, by adding ICommand as a dictionary value type,
// you can add any classes that implement ICommand into the dictionary
Dictionary<string, ICommand> Commands = new Dictionary<string, ICommand>();
// Add commands to dictionary
Commands.Add("hello", new HelloCommand());
Commands.Add("exit", new ExitCommand());
// Example input, load for example from console (user)
string input = "exit"
// If there is a key in the dictionary that equals the user input, the class from value will do ExecuteCommand method
// So if the input is 'exit', the ExitCommand#ExecuteCommand will run
Commands[input].ExecuteCommand();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment