如何在Command-Pattern与C#之间共享命令相同的上下文?

前端之家收集整理的这篇文章主要介绍了如何在Command-Pattern与C#之间共享命令相同的上下文?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在我的应用程序中实现了命令模式(以多支持的方式).

结构体:

  1. class MultiCommand : BaseCommand
  2.  
  3. abstract class BaseCommand : ICommand

工艺流程:

  1. var commandsGroup = new MultiCommand(new List<ICommand>()
  2. {
  3. new Command1(),new Command2(),new Command3(),});
  4.  
  5. commandsGroup.Execute()

现在,假设在Command1中,一个somethingID被改变,并且我将在Command2中使用这个新值.而且,在整个执行过程中还有很多其他属性和对象受到影响.

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

  1. Context.ServerController.something();

IServerController的实例将在multiCommandGroup初始化之前进行.

对于组的所有命令,我如何可以拥有这样的共享上下文?

Context类的例子:

  1. public class CommandContext
  2. {
  3. public IServerController ServerController;
  4. public requiredData Data { get; set; }
  5.  
  6. public CommandContext(){}
  7. }

重要
最低执行代码here

解决方法

1)如果要保留此界面,则必须将此上下文作为构造函数参数传递:
  1. new MultiCommand(new List<ICommand>()
  2. {
  3. new Command1(context),new Command2(context),new Command3(context),})

2)作为另一个选项,您可以接受代表列表而不是命令列表.
MultiCommand将如下所示:

  1. class MultiCommand : ICommand
  2. {
  3. public MultiCommand(List<Func<Context,Command>> commands,Context context)
  4.  
  5. }

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

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

  1. interface IMiddleware<TContext>
  2. {
  3. void Run(TContext context);
  4. }
  5.  
  6. class Chain<TContext>
  7. {
  8. private List<IMiddleware<TContext>> handlers;
  9.  
  10. void Register(IMiddleware<TContext> m);
  11.  
  12. public void Run(TContext context)
  13. {
  14. handlers.ForEach(h => h.Run(context));
  15. }
  16. }

猜你在找的C#相关文章