14

我第一次使用命令模式。我有点不确定我应该如何处理依赖关系。

在下面的代码中,我们调度了一个CreateProductCommand然后排队等待稍后执行。该命令封装了它需要执行的所有信息。

在这种情况下,我们可能需要访问某种类型的数据存储来创建产品。我的问题是,如何将这个依赖注入到命令中以便它可以执行?

public interface ICommand {
    void Execute();
}

public class CreateProductCommand : ICommand {
    private string productName;

    public CreateProductCommand(string productName) {
        this.ProductName = productName;
    }

    public void Execute() {
        // save product
    }
}

public class Dispatcher {
    public void Dispatch<TCommand>(TCommand command) where TCommand : ICommand {
        // save command to queue
    }
}

public class CommandInvoker {
    public void Run() {

        // get queue

        while (true) {
            var command = queue.Dequeue<ICommand>();
            command.Execute();
            Thread.Sleep(10000);
        }
    }
}

public class Client {
    public void CreateProduct(string productName) {
        var command = new CreateProductCommand(productName);
        var dispatcher = new Dispatcher();
        dispatcher.Dispatch(command);
    }
}

非常感谢

4

1 回答 1

16

查看您的代码后,我建议不要使用命令模式,而是使用命令数据对象和命令处理程序:

public interface ICommand { }

public interface ICommandHandler<TCommand> where TCommand : ICommand {
    void Handle(TCommand command);
}

public class CreateProductCommand : ICommand { }

public class CreateProductCommandHandler : ICommandHandler<CreateProductCommand> {
    public void Handle(CreateProductCommand command) {

    }
}

此方案更适合 CreateProductCommand 可能需要跨越应用程序边界的情况。此外,您可以使用配置了所有依赖项的 DI 容器解析 CreateProductCommand 的实例。调度程序或“消息总线”将在接收到命令时调用处理程序。

这里查看一些背景信息。

于 2011-07-07T23:50:21.130 回答