Last active
January 6, 2025 00:37
-
-
Save profiiqus/9c8f3ac6545012cd3f7b80692c6c68b4 to your computer and use it in GitHub Desktop.
Command Pattern in C#
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
// 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