Junior — Middle
Can you explain what is meant by the command pattern in programming?
sobes.tech AI
Answer from AI
The "Command" pattern is a behavioral design pattern that encapsulates a request as an object, allowing parameterization of clients with different requests, queuing or logging requests, and supporting undo operations.
The main idea is to separate the object that invokes the operation from the object that performs it. The command contains all the information needed to perform the action, including the method and parameters.
Example in C#:
// Command interface
public interface ICommand
{
void Execute();
}
// Concrete command
public class LightOnCommand : ICommand
{
private Light _light;
public LightOnCommand(Light light) { _light = light; }
public void Execute() { _light.TurnOn(); }
}
// Receiver
public class Light
{
public void TurnOn() { Console.WriteLine("Light is on"); }
}
// Client
var light = new Light();
ICommand command = new LightOnCommand(light);
command.Execute();
This approach simplifies the extension and maintenance of the code, especially when implementing complex control scenarios.