命令模式:如何将参数传递到一个命令? [英] Command Pattern : How to pass parameters to a command?

查看:199
本文介绍了命令模式:如何将参数传递到一个命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是有关命令模式,在那里我们有以下的抽象(C#代码):

My question is related to the command pattern, where we have the following abstraction (C# code) :

public interface ICommand
{
    void Execute();
}

让我们以一个简单的具体命令,其目的是从我们的应用程序中删除一个实体。 A 实例,例如

Let's take a simple concrete command, which aims to delete an entity from our application. A Person instance, for example.

我将有一个 DeletePersonCommand ,它实现了的ICommand 。此命令需要在删除作为参数,以便删除它时,执行方法被调用。

I'll have a DeletePersonCommand, which implements ICommand. This command needs the Person to delete as a parameter, in order to delete it when Execute method is called.

什么是管理命令,参数化的最佳方式?如何将参数传递到命令,执行它们之前?

What is the best way to manage parametrized commands ? How to pass parameters to commands, before executing them ?

推荐答案

您需要的参数与命令对象相关联,无论是通过构造函数或setter注入(或同等学历)。也许是这样的:

You'll need to associate the parameters with the command object, either by constructor or setter injection (or equivalent). Perhaps something like this:

public class DeletePersonCommand: ICommand
{
     private Person personToDelete;
     public DeletePersonCommand(Person personToDelete)
     {
         this.personToDelete = personToDelete;
     }

     public void Execute()
     {
        doSomethingWith(personToDelete);
     }
}

这篇关于命令模式:如何将参数传递到一个命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆