gpt4 book ai didi

c# - 如何使用 C# 在命令模式中的命令之间共享相同的上下文?

转载 作者:太空狗 更新时间:2023-10-29 17:33:57 25 4
gpt4 key购买 nike

我已经在我的应用程序中实现了命令模式(以多支持方式)。

结构:

class MultiCommand : BaseCommand

abstract class BaseCommand : ICommand

流程:

   var commandsGroup = new MultiCommand(new List<ICommand>()
{
new Command1(),
new Command2(),
new Command3(),
});

commandsGroup.Execute()

现在,假设 Command1 中的 somethingID 发生了变化,我将在 Command2 中使用这个新值……而且,在整个执行过程中,有很多其他属性对象受到影响。

此外,还有一些接口(interface)实现应该可以在任何命令中使用上下文对象,例如:

Context.ServerController.something();

IServerController 的实例化将发生在 multiCommandGroup 初始化之前。

如何为组中的所有命令共享一个上下文

上下文类的例子:

public class CommandContext
{
public IServerController ServerController;
public RequiredData Data { get; set; }

public CommandContext(){}
}

重要一个最小的实现代码是 here

最佳答案

1) 如果你想保留这个接口(interface),那么你必须将这个上下文作为构造函数参数传递:

new MultiCommand(new List<ICommand>()
{
new Command1(context),
new Command2(context),
new Command3(context),
})

2) 作为另一种选择,您可以接受委托(delegate)列表而不是命令列表。MultiCommand 将如下所示:

class MultiCommand : ICommand
{
public MultiCommand(List<Func<Context, Command>> commands, Context context)

}

这几乎是一样的,除了 MultiCommand 负责所有命令共享相同的上下文。

3) 看起来 MultiCommand 中的命令取决于上一个命令的结果。在这种情况下,命令模式可能不是最好的。也许你应该尝试在这里实现中间件链?

interface IMiddleware<TContext>
{
void Run(TContext context);
}

class Chain<TContext>
{
private List<IMiddleware<TContext>> handlers;

void Register(IMiddleware<TContext> m);

public void Run(TContext context)
{
handlers.ForEach(h => h.Run(context));
}
}

关于c# - 如何使用 C# 在命令模式中的命令之间共享相同的上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37884056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com