3

I know how to implement a Command Design pattern as follows:

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

Say I inherit this ,as an example:

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

Problem is to use this ConnectionCommand I need to first instantiate an object, but the commands are context free, so I would prefer to not have to instantiate anything to run the ConnectionCommand's Execute method. (P.S. the ConnectionCommand.Execute() will be run from an event ,in a delegate).

How would I recreate this kind of design pattern but allowing the methods to be statically called?

4
  • What does "context-free" mean here? Commented Jun 2, 2015 at 11:37
  • They don't require specific instance information to execute. They are just called from any other class and they do something without needing to know anything about the class that's calling them. Much like a static method might be used. Commented Jun 2, 2015 at 11:48
  • 2
    It seems that you have a leaky abstraction here: your abstract class has a string connectionString parameter, which implies some sort of connection command already. Commented Jun 2, 2015 at 11:51
  • Not the actual code, just an example . Yeah I spotted that too late . :P Commented Jun 2, 2015 at 12:03

3 Answers 3

8

Delegates are C#'s built-in implementation of the command pattern. Why re-invent the wheel; use delegates, which support static, pure functions automatically.

So you have an event system and those events invoke delegates. You need those delegates to have state though, without creating instances of some class. That's where closures come in to play. 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.
    }
}
Sign up to request clarification or add additional context in comments.

8 Comments

I agree with this, problem is some of the commands don't just have their Execute method, they sometimes have Property lists, private methods ,etc. I wanted a Command base class to allow any such Command to be Executed from an event and this would use that Command class to do a bunch of stuff. Silimar to what Justin Harvey said bellow.
Wouldn't this still require instantiating ConnectionCommand class?
Yes , yes it would :P. Which is precisely my problem .
@BradleyMorris, if you want an OO-based command pattern, then instances of the command objects have to be instantiated somewhere. If you are using events, then you are already using delegates, so why would you then want the GoF command pattern on top of that? I must have misunderstood your question as I'm now confused as to what you want to do.
Exactly! How can you have base and sub classes with static methods? You have gotta pick one. Or create a utility class with static methods.
|
0

I've used a 'CommandProcessor' when I've used this pattern:

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

It is then used as such:

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

It works nicely as your processor can effectively employ a 'pipe and filter' pattern to add cross-cutting concerns.

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

3 Comments

That seems like it might help solve my problem. Except it still requires instantiation, but at least it will neaten up my current code.
It is neat. I use a generic version with Castle Windsor and let it handle my instantiation. You end-up with: CommandProcessor.Execute<ConnectionCommand>();
Both of these answers seem to be very good, I'll try out both and see which one better fits my code( can't just yet, bit busy ).
0

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

A 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 do the Command Design pattern in C# using closure and a Factory, similar to an answer above but without state information. Still I've added it for completeness. The Commands.MovePiece can then be subscribed to an appropriate event to get triggered.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.