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

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

问题描述

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

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

public interface ICommand
{
    void Execute();
}

让我们采用一个简单的具体命令,该命令旨在从我们的应用程序中删除一个实体.例如,一个 Person 实例.

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

我将有一个 DeletePersonCommand,它实现了 ICommand.该命令需要将Person作为参数删除,以便在调用Execute方法时删除.

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天全站免登陆