# Behavioral patterns show code real world examples: Command Pattern

### **Understanding Software Behavioral Design Patterns**

### **Introduction**

The Command Pattern is a fundamental behavioral design pattern in software development that addresses the encapsulation of requests as independent objects. This technique is valuable because it allows requests to be converted into objects containing all the necessary information to execute the request at a later time, parameterize methods with different requests, and support undoable operations.

This pattern is particularly useful for separating the execution logic of requests from their invocation, facilitating the management of complex actions and controlling their execution at specific times. By encapsulating requests as objects, the Command Pattern offers flexibility by enabling the creation of commands with different purposes and the ability to reuse them in multiple contexts without modifying existing code.

In an environment where modularity and code reuse are essential, the Command Pattern stands out for its ability to improve code organization and maintainability. By separating requests from their direct execution, it becomes easier to add new functionalities and adapt the system to changes in requirements without compromising its integrity.

Furthermore, this pattern promotes scalability by allowing the construction of composite commands and efficient transaction management. This results in a more robust and extensible design, where actions can be encapsulated clearly and coherently, facilitating collaboration among development teams and the continuous evolution of the software.

**Key Development Concepts**

Communication and interaction between objects can be complex and difficult to manage, especially in large and complex systems. Behavior patterns, such as the Command Pattern, offer a structured and predictable way to manage this communication and interaction, facilitating the creation of more sustainable and scalable systems.

By using behavioral patterns, developers can create more flexible and scalable systems. These patterns help decouple objects, making it easier to add or remove objects without affecting the entire system (Gamma et al., 1994). The command pattern specifically addresses encapsulation of requests as objects, allowing for lazy execution, parameterization of methods with different requests, and support for undoable operations.

Behavioral patterns play a crucial role in making software systems easier to maintain by providing a clear and consistent way of organizing interactions between objects (Gamma et al., 1994). This aspect of maintainability is vital in software development due to the long lifespan of systems and constant changes.

Additionally, the command pattern provides a model for organizing interactions between objects. They offer a clear and consistent way to manage dependencies, coordinate actions, and handle complex interactions. By using this model, developers can create systems that are more predictable, easier to understand, and also improve system security and reliability. These structured patterns help prevent errors and system failures by systematically managing communication and interaction between objects (Gamma et al., 1994).

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1714096713612/5e6b1ca9-1ab7-444c-8e4f-7df3cfa20073.png align="center")

**Behavioral Design Patterns**

**Command Pattern:** "This pattern separates the request for an action from the action itself. It encapsulates a request as an object, allowing for easy storage, parameterization, and queuing of requests" (Gamma et al., 1994).

**Real-world example 02 (Command Pattern):**

This code provides an example of the Command design pattern in C#. Here's a brief explanation:

\- It defines an interface `ICommand` with an `Execute` method.

\- It implements two command classes: `SimpleCommand`, which performs a simple action (printing a message), and `ComplexCommand`, which delegates more complex operations to a "receiver" object (\`Receiver\`).

\- The `Receiver` object contains the business logic to carry out requested operations.

\- The `Invoker` object is associated with one or more commands and sends requests to the command to execute actions.

\- In the `Main` method, an `Invoker` is created, commands (\`SimpleCommand\` and `ComplexCommand`) are assigned to it, and an important operation is executed through the `Invoker`.

using System;

namespace RefactoringGuru.DesignPatterns.Command.Conceptual

{

// The Command interface declares a method for executing a command.

public interface ICommand

{

void Execute();

}

// Some commands can implement simple operations on their own.

class SimpleCommand : ICommand

{

private string \_payload = string.Empty;

public SimpleCommand(string payload)

{

this.\_payload = payload;

}

public void Execute()

{

Console.WriteLine($"SimpleCommand: See, I can do simple things like printing ({this.\_payload})");

}

}

// However, some commands can delegate more complex operations to other

// objects, called "receivers."

class ComplexCommand : ICommand

{

private Receiver \_receiver;

// Context data, required for launching the receiver's methods.

private string \_a;

private string \_b;

// Complex commands can accept one or several receiver objects along

// with any context data via the constructor.

public ComplexCommand(Receiver receiver, string a, string b)

{

this.\_receiver = receiver;

this.\_a = a;

this.\_b = b;

}

// Commands can delegate to any methods of a receiver.

public void Execute()

{

Console.WriteLine("ComplexCommand: Complex stuff should be done by a receiver object.");

this.\_receiver.DoSomething(this.\_a);

this.\_receiver.DoSomethingElse(this.\_b);

}

}

// The Receiver classes contain some important business logic. They know how

// to perform all kinds of operations, associated with carrying out a

// request. In fact, any class may serve as a Receiver.

class Receiver

{

public void DoSomething(string a)

{

Console.WriteLine($"Receiver: Working on ({a}.)");

}

public void DoSomethingElse(string b)

{

Console.WriteLine($"Receiver: Also working on ({b}.)");

}

}

// The Invoker is associated with one or several commands. It sends a

// request to the command.

class Invoker

{

private ICommand \_onStart;

private ICommand \_onFinish;

// Initialize commands.

public void SetOnStart(ICommand command)

{

this.\_onStart = command;

}

public void SetOnFinish(ICommand command)

{

this.\_onFinish = command;

}

// The Invoker does not depend on concrete command or receiver classes.

// The Invoker passes a request to a receiver indirectly, by executing a

// command.

public void DoSomethingImportant()

{

Console.WriteLine("Invoker: Does anybody want something done before I begin?");

if (this.\_onStart is ICommand)

{

this.\_onStart.Execute();

}

Console.WriteLine("Invoker: ...doing something really important...");

Console.WriteLine("Invoker: Does anybody want something done after I finish?");

if (this.\_onFinish is ICommand)

{

this.\_onFinish.Execute();

}

}

}

class Program

{

static void Main(string\[\] args)

{

// The client code can parameterize an invoker with any commands.

Invoker invoker = new Invoker();

invoker.SetOnStart(new SimpleCommand("Say Hi!"));

Receiver receiver = new Receiver();

invoker.SetOnFinish(new ComplexCommand(receiver, "Send email", "Save report"));

invoker.DoSomethingImportant();

}

}

}

**Conclusion**

The Command Pattern emerges as a powerful tool within the realm of behavioral design patterns in software development. Its ability to encapsulate requests as independent objects not only facilitates the management of communication and interaction between objects but also significantly contributes to creating more flexible, scalable, and maintainable systems.

By separating the execution logic of requests from their direct invocation, the Command Pattern provides a structured and predictable approach to handling complex actions, coordinating operations, and managing dependencies. This not only enhances code organization and the system's adaptability to changing requirements but also promotes system security and reliability by preventing errors and failures.

In conclusion, the Command Pattern represents a proven and effective solution to common challenges in communication and interaction between objects in software development. Its adoption and understanding by developers not only improve code efficiency and maintainability but also provide a solid foundation for building robust and scalable systems in dynamic and demanding environments.

**BIBLIOGRAPHY:**

Gamma, E., Helm, R., Johnson, R., & Vlissides, J. (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley Professional.

GoF (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley Professional.

Design Patterns in C#. (n.d.). Refactoring.guru. Retrieved April 18, 2024, from [https://refactoring.guru/es/design-patterns/csharp](https://refactoring.guru/es/design-patterns/csharp)
