Using Command Pattern with C#: Basic Information and Examples

Using Command Pattern with C#: Basic Information and Examples


In software development processes, design patterns play an important role. In this article, we will discuss the Command Pattern design pattern, which you can use in the C# language. Command Pattern provides flexibility and scalability in software by representing requests or operations with objects. This pattern is commonly used in situations such as user interfaces, action logs, or operation queue applications.

What is the Command Pattern?

The Command Pattern is a design pattern that allows a request to be represented as an object. In this way, we can manage operations in an object-oriented manner. It usually includes three main components: the Command interface, ConcreteCommand classes, and the Client. The Command interface defines a method that all concrete command classes must implement. ConcreteCommand classes perform specific operations by implementing this interface. The Client creates command objects and sends them to a receiver object.

Command Pattern Implementation Example

Below is an example of using the Command Pattern. In this example, we will create a command object to perform user operations.

1. Command Interface

public interface ICommand
{
    void Execute();
}

2. Concrete Command Class

public class TurnOnLightCommand : ICommand
{
    private readonly Light _light;

    public TurnOnLightCommand(Light light)
    {
        _light = light;
    }

    public void Execute()
    {
        _light.TurnOn();
    }
}

3. Receiver Class

public class Light
{
    public void TurnOn() => Console.WriteLine("Light is ON");
    public void TurnOff() => Console.WriteLine("Light is OFF");
}

4. Client Class

public class Client
{
    public static void Main(string[] args)
    {
        Light light = new Light();
        ICommand turnOnLight = new TurnOnLightCommand(light);
        turnOnLight.Execute();  // Output: Light is ON
    }
}

Conclusion

The Command Pattern is an important pattern that ensures flexibility and ease of maintenance in software development processes. By using this pattern in the C# language, you can represent operations with objects and manage them more easily. However, as with every design pattern, it is important to carefully evaluate your application's needs before using the Command Pattern. This way, you can make the best use of design patterns.