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...

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 ...

.NET 10: Your Ultimate Guide to the Coolest New Features (with Real-World Goodies!)

 Hey .NET warriors! 🤓 Are you ready to explore the latest and greatest features that .NET 10 and C# 14 bring to the table? Whether you're a seasoned developer or just starting out, this guide will show you how .NET 10 makes your apps faster, safer, and more productive — with real-world examples to boot! So grab your coffee ☕️ and let’s dive into the awesome . 💪 1️⃣ JIT Compiler Superpowers — Lightning-Fast Apps .NET 10 is all about speed . The Just-In-Time (JIT) compiler has been turbocharged with: Stack Allocation for Small Arrays 🗂️ Think fewer heap allocations, less garbage collection, and blazing-fast performance . Better Code Layout 🔥 Hot code paths are now smarter, meaning faster method calls and fewer CPU cache misses. 💡 Why you care: Your APIs, desktop apps, and services now respond quicker — giving users a snappy experience . 2️⃣ Say Hello to C# 14 — More Power in Your Syntax .NET 10 ships with C# 14 , and it’s packed with developer goodies: Field-Bac...