Implementing the Command Design Pattern with C # Static Methods

I know how to implement the Command Design pattern like this:

public abstract class Command
{
   public abstract void Execute(string someString);
}

      

Let's say I inherit this, for example:

public class ConnectionCommand : Command
{
   public override void Execute(string connectionString)
   {
      ...do some stuff here...;
   }
}

      

The problem is using this ConnectionCommand. I need to instantiate the object first, but the commands are context free, so I would rather not create any instances to run the ConnectionCommand Execute method. (PS ConnectionCommand.Execute () will be fired from an event in the delegate).

How do I recreate a design pattern like this, but allows methods to be called statically?

+3


source to share


3 answers


Delegates are a built-in implementation of the C # command pattern. Why reinvent the wheel; use delegates that automatically support static, pure functions.

So, you have an event system and these events trigger delegates. However, these delegates must be stateful without instantiating any class. This is where adventure closes. As an example:



public class SomeClass
{
    public static CreateCommand(SomeType state, SomeEventHandler eventHandler)
    {
        eventHandler += (s, e) => MyDelegate(state, s, e);
    }

    private static void MyDelegate(SomeType state, object sender, EventArgs e)
    {
        // do something with state, when the event is fired.
    }
}

      

+8


source


I used "CommandProcessor" when I used this template:

class CommandProcessor
{
    static void Execute(ICommand command)
    {
        command.Execute();
    }
}

      

Then it is used as such:



CommandProcessor.Execute(new ConnectionCommand {PropertyX = 1, ProperyY = 2});

      

It works great as your processor can effectively use the "pipe and filter" pattern to add crosscutting concerns.

It can be improved with generics and overloads for parameters / return values, etc.

0


source


http://journal.stuffwithstuff.com/2009/07/02/closures-and-the-command-pattern/

Link to some of Bob Nystrom's stuff. Using closures:

static class Commands
{
    // create a command to move a piece
    public static Action MovePiece(Piece piece, int x, int y)
    {
        return () => piece.MoveTo(x, y);
    }
}

class Program
{
    public static Main(string[] args)
    {
        // ui or ai creates command
        var piece = new Piece();
        var command =  Commands.MovePiece(piece, 3, 4);

        // chess engine invokes it
        command();
    }
}

      

A very neat way to create a command design pattern in C # using closures and Factory, similar to the answer above, but without state information. However, I have added it for completeness. Then Commands.MovePiece can be subscribed to the appropriate triggering event.

0


source







All Articles