SOLID & Design Patterns Interview Question #37
What is the Command Pattern?
Structural, Creational & Behavioral Patterns Junior Beginner
Quick Interview Answer
The Command Pattern encapsulates a request as an object. The object can contain the information needed to perform an operation and can be passed, queued, logged, retried, or decorated independently of the caller.
Detailed Explanation
The Command Pattern encapsulates a request as an object. The object can contain the information needed to perform an operation and can be passed, queued, logged, retried, or decorated independently of the caller.
Command-style designs are useful for application use cases such as CreateOrder, SendInvoice, or ApproveRequest. The pattern separates the requester from the object that executes the behavior.
Code Example
public record CreateOrderCommand(
int CustomerId,
IReadOnlyList<int> ProductIds);
public interface ICommandHandler<TCommand>
{
Task HandleAsync(TCommand command);
}