
C# Design Patterns: The Command Pattern
đź§© What is the Command Pattern?
The Command Pattern is a way to turn a request (like pressing a button) into an object. This lets you store, pass, and undo commands easily.
Think of a TV remote. Each button (like Power or Volume Up) sends a command to the TV. The remote doesn't care how the TV works—it just sends a signal.
đź› Real Life Example
Imagine a smart home app. You can tap a button to turn on the lights, start the coffee maker, or lock the doors. Each of these actions is a "command" you can send.
âś… Pros (Why use it?)
- Easy to undo actions – You can save commands and undo them later.
- Loose coupling – The button doesn't need to know how the light turns on.
- Flexibility – You can queue, log, or even delay commands.
❌ Cons (Things to watch out for)
- More code – You'll need to make a new class for each command.
- Can feel overkill for small projects.
đź§Ş Let's Build It in C#
Step 1: Make a Command Interface
public interface ICommand
{
void Execute();
void Undo();
}
Step 2: Create a Receiver (the thing that does the work)
public class Light
{
public void TurnOn() => Console.WriteLine("Light is ON");
public void TurnOff() => Console.WriteLine("Light is OFF");
}
Step 3: Create Command Classes
public class LightOnCommand : ICommand
{
private Light _light;
public LightOnCommand(Light light)
{
_light = light;
}
public void Execute() => _light.TurnOn();
public void Undo() => _light.TurnOff();
}
Step 4: Create the Invoker (like the remote control)
public class RemoteControl
{
private ICommand _command;
public void SetCommand(ICommand command)
{
_command = command;
}
public void PressButton()
{
_command.Execute();
}
public void PressUndo()
{
_command.Undo();
}
}
Step 5: Use It!
class Program
{
static void Main()
{
Light livingRoomLight = new Light();
ICommand lightOn = new LightOnCommand(livingRoomLight);
RemoteControl remote = new RemoteControl();
remote.SetCommand(lightOn);
remote.PressButton(); // Light is ON
remote.PressUndo(); // Light is OFF
}
}
đź§ Summary
| Concept | Description |
|---|---|
| Command | Object that does a task (like turn on light) |
| Receiver | Knows how to do the task (like the Light) |
| Invoker | Asks the command to run (like the Remote) |
The Command Pattern is great when you need buttons, menus, undo features, or to queue up actions. It helps you stay organized and flexible—just be mindful of the extra code!