IConfiguration vs IOptions NET
Synchronous and Asynchronous in .NET Core
Model Binding and Validation in ASP.NET Core
ControllerBase vs Controller in ASP.NET Core
ConfigureServices and Configure methods
IHostedService interface in .NET Core
ASP.NET Core request processing
| Test-Driven Development (TDD) :👈 | 👉:Observer-Pattern |
Command Pattern C# |
The Command Pattern is a behavioral design pattern that encapsulates a request as an object, thereby allowing you to parameterize clients with different requests, queue or log requests, and support undoable operations.
Execute() method.Command interface and defines the binding between a receiver and an action.Letβs imagine a simple Remote Control system for a light.
// Command Interface
public interface ICommand
{
void Execute();
void Undo();
}
// Receiver
public class Light
{
public void TurnOn()
{
Console.WriteLine("Light is ON");
}
public void TurnOff()
{
Console.WriteLine("Light is OFF");
}
}
// Concrete Commands
public class LightOnCommand : ICommand
{
private Light _light;
public LightOnCommand(Light light)
{
_light = light;
}
public void Execute()
{
_light.TurnOn();
}
public void Undo()
{
_light.TurnOff();
}
}
public class LightOffCommand : ICommand
{
private Light _light;
public LightOffCommand(Light light)
{
_light = light;
}
public void Execute()
{
_light.TurnOff();
}
public void Undo()
{
_light.TurnOn();
}
}
// Invoker
public class RemoteControl
{
private ICommand _command;
public void SetCommand(ICommand command)
{
_command = command;
}
public void PressButton()
{
_command.Execute();
}
public void PressUndo()
{
_command.Undo();
}
}
// Client
class Program
{
static void Main(string[] args)
{
Light livingRoomLight = new Light();
ICommand lightOn = new LightOnCommand(livingRoomLight);
ICommand lightOff = new LightOffCommand(livingRoomLight);
RemoteControl remote = new RemoteControl();
// Turn light ON
remote.SetCommand(lightOn);
remote.PressButton();
// Undo (turn light OFF)
remote.PressUndo();
// Turn light OFF
remote.SetCommand(lightOff);
remote.PressButton();
// Undo (turn light ON)
remote.PressUndo();
}
}
Light is ON Light is OFF Light is OFF Light is ON
| Test-Driven Development (TDD) :👈 | 👉:Observer-Pattern |