开发者

Is this just a functional implementation of the Command pattern?

开发者 https://www.devze.com 2023-01-30 16:43 出处:网络
Recently I\'ve found my self to implement code following a pattern like: public class SomeClass() { private T Execute<T>(Func<T> function)

Recently I've found my self to implement code following a pattern like:

public class SomeClass()
{
    private T Execute<T>(Func<T> function)
    {
        // Do some common stuff for every function like logging and try-catch
        function();
    }

    public Type1 Command1()
    {
        Execute<Type1>(() => funcForCommand1);
    }

    public Type2 Command2()
    {
        Execute<Type2>(() => funcForCommand2);
    }
}

Is this just a functio开发者_JAVA百科nal approach on the CommandPattern? Depending on the situation I've different version of this? You could probably achieve exactly the same thing by letting funcForCommandX inherit from somekind of ICommand that defines the Execute function, but I like my way in many situations better since most of the time the commands are only used in one location in the code and not needs to be exposed to the rest of the code. Of course you should implement the real command pattern if it is used in more locations in the code.


It is up to your needs. That is all I can say.

But I would like to state that this is not a Command Pattern but may be a method delegation.

Command Pattern focuses mainly on execution of a method/task. Following are standard behaviors that can be expected from a Command in this pattern:

  • Undo/Redo
  • Transactions
  • Composite Command Execution
  • Macros

When you wrap a method/task implementation in a Command, you can provide implementations on what to do to reverse/undo what has been done. Provide default implementation on attaching current execution to transactions, macro recording, thread-safe execution, etc.

With your approach you don't have that. And it's not easily doable until you wrap each task/method in a Command wrapper and provide above mentioned behaviors.

Take a look at Wikipedia article for further details on a Command Pattern.

0

精彩评论

暂无评论...
验证码 换一张
取 消