Post Details

What is the Command Design Pattern in C Sharp .Net ?

np

Fri , Aug 04 2023

np

Article 4 on design pattern-

The Command Design Pattern

The Command Design Pattern is a behavioral design pattern that encapsulates a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. It is used when you want to decouple an object that invokes an operation from the one that knows how to perform it. Here is an example of the Command Design Pattern in C#:

using System;

public interface ICommand

{

    void Execute();

}

public class Receiver

{

    public void Action()

    {

        Console.WriteLine("Receiver.Action() called");

    }

}

public class ConcreteCommand : ICommand

{

    private readonly Receiver _receiver;

    public ConcreteCommand(Receiver receiver)

    {

        _receiver = receiver;

    }

    public void Execute()

    {

        _receiver.Action();

    }

}

public class Invoker

{

    private ICommand _command;

    public void SetCommand(ICommand command)

    {

        _command = command;

    }

    public void ExecuteCommand()

    {

        _command.Execute();

    }

}


Leave a Reply

Please log in to Comment On this post.