Skip to main content

Understanding the Command Design Pattern in C#

 

The Command design pattern is a behavioral pattern that turns a request into a stand-alone object that contains all information about the request. This transformation allows for parameterizing methods with different requests, queuing or logging requests, and supporting undoable operations.

Understanding the State Design Pattern in C#

Let's consider a scenario with a text editor application that supports basic text operations like writing text and undoing the last operation.

Example without Command Design Pattern

using System;

namespace WithoutCommandPattern
{
    class TextEditor
    {
        public string Text { get; private set; } = "";

        public void Write(string text)
        {
            Text += text;
            Console.WriteLine($"Text after write: {Text}");
        }

        public void UndoWrite(string text)
        {
            if (Text.EndsWith(text))
            {
                Text = Text.Substring(0, Text.Length - text.Length);
                Console.WriteLine($"Text after undo: {Text}");
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            TextEditor editor = new TextEditor();

            // Write operations
            editor.Write("Hello ");
            editor.Write("World!");

            // Undo operations
            editor.UndoWrite("World!");
            editor.UndoWrite("Hello ");
        }
    }
}

Problems in the Non-Pattern Approach

  1. Tight Coupling: The Program class is tightly coupled with the TextEditor class's methods. Any change in the method signature or behavior of TextEditor requires changes in the Program class.

  2. Scalability: If more operations need to be added (e.g., redo, cut, paste), the Program class will become cluttered with logic for these operations. Managing a complex series of operations and their undo functionality becomes cumbersome.

  3. Lack of Abstraction: The operations are directly called on the TextEditor object. There's no abstraction for the actions (write, undo), making it harder to extend or modify behavior without changing the calling code.

  4. Command History: There's no built-in mechanism to keep a history of executed commands. Implementing a command history manually within Program would be error-prone and cumbersome.
How Command Pattern Solves These Problems
  1. Decoupling: The Command Pattern decouples the invoker (Program/TextEditorInvoker) from the receiver (TextEditor). The invoker only knows about the ICommand interface, making it easier to modify the receiver's methods without affecting the invoker.

  2. Scalability: New commands can be added by implementing the ICommand interface. This approach keeps the Program and TextEditorInvoker classes clean and focused on command execution and management rather than the details of each operation.

  3. Abstraction: The ICommand interface abstracts the actions, allowing for more flexible and maintainable code. This abstraction makes it easier to change the implementation of an action without modifying the client code.

  4. Command History: The invoker maintains a stack of executed commands, enabling easy implementation of undo functionality. This built-in history management is cleaner and less error-prone.

Revisited Code with Command Pattern

Here is how we can implement this pattern:

using System;
using System.Collections.Generic;

namespace CommandPattern
{
    // Command interface
    interface ICommand
    {
        void Execute();
        void Unexecute();
    }

    // Receiver class
    class TextEditor
    {
        public string Text { get; private set; } = "";

        public void Write(string text)
        {
            Text += text;
            Console.WriteLine($"Text after write: {Text}");
        }

        public void UndoWrite(string text)
        {
            if (Text.EndsWith(text))
            {
                Text = Text.Substring(0, Text.Length - text.Length);
                Console.WriteLine($"Text after undo: {Text}");
            }
        }
    }

    // Concrete command for writing text
    class WriteCommand : ICommand
    {
        private readonly TextEditor _editor;
        private readonly string _text;

        public WriteCommand(TextEditor editor, string text)
        {
            _editor = editor;
            _text = text;
        }

        public void Execute()
        {
            _editor.Write(_text);
        }

        public void Unexecute()
        {
            _editor.UndoWrite(_text);
        }
    }

    // Invoker class
    class TextEditorInvoker
    {
        private readonly Stack<ICommand> _commands = new Stack<ICommand>();

        public void ExecuteCommand(ICommand command)
        {
            command.Execute();
            _commands.Push(command);
        }

        public void Undo()
        {
            if (_commands.Count > 0)
            {
                ICommand command = _commands.Pop();
                command.Unexecute();
            }
            else
            {
                Console.WriteLine("No commands to undo.");
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            TextEditor editor = new TextEditor();
            TextEditorInvoker invoker = new TextEditorInvoker();

            ICommand writeHello = new WriteCommand(editor, "Hello ");
            ICommand writeWorld = new WriteCommand(editor, "World!");

            invoker.ExecuteCommand(writeHello);
            invoker.ExecuteCommand(writeWorld);

            invoker.Undo(); // Should undo "World!"
            invoker.Undo(); // Should undo "Hello "
            invoker.Undo(); // No commands to undo
        }
    }
}

Why Can't We Use Other Design Patterns Instead?

  • Strategy Pattern: The Strategy pattern defines a family of algorithms and allows the client to choose which algorithm to use. It does not encapsulate the request and its parameters.

  • State Pattern: The State pattern allows an object to alter its behavior when its internal state changes. It is more suitable for managing state transitions rather than encapsulating requests.

  • Observer Pattern: The Observer pattern defines a one-to-many dependency between objects, where one object notifies its dependents of state changes. It is not designed for encapsulating requests and operations.

Steps to Identify Use Cases for the Command Pattern

  1. Encapsulation of Requests: Identify scenarios where requests need to be encapsulated as objects.

  2. Undo/Redo Functionality: Ensure that the operations require undo and redo functionality.

  3. Parameterization and Queuing: Consider the Command pattern when requests need to be parameterized and queued.

  4. Decoupling Sender and Receiver: Use the Command pattern to decouple the sender of a request from the object that performs the request.

By following these steps and implementing the Command pattern, you can achieve encapsulated requests, support for undo and redo operations, and decoupling of senders and receivers, improving flexibility and maintainability in your system.

Comments

Popular posts from this blog

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...

Clean Architecture: What It Is and How It Differs from Microservices

In the tech world, buzzwords like   Clean Architecture   and   Microservices   often dominate discussions about building scalable, maintainable applications. But what exactly is Clean Architecture? How does it compare to Microservices? And most importantly, is it more efficient? Let’s break it all down, from understanding the core principles of Clean Architecture to comparing it with Microservices. By the end of this blog, you’ll know when to use each and why Clean Architecture might just be the silent hero your projects need. What is Clean Architecture? Clean Architecture  is a design paradigm introduced by Robert C. Martin (Uncle Bob) in his book  Clean Architecture: A Craftsman’s Guide to Software Structure and Design . It’s an evolution of layered architecture, focusing on organizing code in a way that makes it  flexible ,  testable , and  easy to maintain . Core Principles of Clean Architecture Dependency Inversion : High-level modules s...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...