.NET设计模式(17):命令模式(Command Pattern)

命令模式(Command Pattern

——.NET设计模式系列之十七

TerryLee20067

概述

在软件系统中,“行为请求者”与“行为实现者”通常呈现一种“紧耦合”。但在某些场合,比如要对行为进行“记录、撤销/重做、事务”等处理,这种无法抵御变化的紧耦合是不合适的。在这种情况下,如何将“行为请求者”与“行为实现者”解耦?将一组行为抽象为对象,可以实现二者之间的松耦合[李建忠]。这就是本文要说的Command模式。

意图

将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤消的操作。[GOF 《设计模式》]

结构图

Command模式结构图如下:

1  Command模式结构图

生活中的例子

Command模式将一个请求封装为一个对象,从而使你可以使用不同的请求对客户进行参数化。用餐时的账单是Command模式的一个例子。服务员接受顾客的点单,把它记在账单上封装。这个点单被排队等待烹饪。注意这里的"账单"是不依赖于菜单的,它可以被不同的顾客使用,因此它可以添入不同的点单项目。

2  使用用餐例子的Command模式对象图

Command模式解说

在众多的设计模式中,Command模式是很简单也很优雅的一种设计模式。Command模式它封装的是命令,把命令发出者的责任和命令执行者的责任分开。我们知道,一个类是一组操作和相应的一些变量的集合,现在有这样一个类Document,如下:

3

示意性代码:

ExpandedBlockStart.gif ContractedBlock.gif /**/ /// <summary>
InBlock.gif
InBlock.gif
/// 文档类
InBlock.gif
ExpandedBlockEnd.gif
/// </summary>

None.gif
None.gif
public   class  Document
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif
InBlock.gif    
/// 显示操作
InBlock.gif
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif
InBlock.gif    
public void Display()
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        Console.WriteLine(
"Displaydot.gif");
ExpandedSubBlockEnd.gif    }
 
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif
InBlock.gif    
/// 撤销操作
InBlock.gif
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif
InBlock.gif    
public void Undo()
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        Console.WriteLine(
"Undodot.gif");
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif
InBlock.gif    
/// 恢复操作
InBlock.gif
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif
InBlock.gif    
public void Redo()
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        Console.WriteLine(
"Redodot.gif");
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

一般情况下我们使用这个类的时候,都会这样去写:

None.gif class  Program
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
static void Main(string[] args)
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        Document doc 
= new Document();
InBlock.gif
InBlock.gif        doc.Display();
InBlock.gif
InBlock.gif        doc.Undo();
InBlock.gif
InBlock.gif        doc.Redo();
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

这样的使用本来是没有任何问题的,但是我们看到在这个特定的应用中,出现了Undo/Redo的操作,这时如果行为的请求者和行为的实现者之间还是呈现这样一种紧耦合,就不太合适了。可以看到,客户程序是依赖于具体Document的命令(方法)的,引入Command模式,需要对Document中的三个命令进行抽象,这是Command模式最有意思的地方,因为在我们看来Display()Undo()Redo()这三个方法都应该是Document所具有的,如果单独抽象出来成一个命令对象,那就是把函数层面的功能提到了类的层面,有点功能分解的味道,我觉得这正是Command模式解决这类问题的优雅之处,先对命令对象进行抽象:

4

示意性代码:

ExpandedBlockStart.gif ContractedBlock.gif /**/ /// <summary>
InBlock.gif
InBlock.gif
/// 抽象命令
InBlock.gif
ExpandedBlockEnd.gif
/// </summary>

None.gif
None.gif
public   abstract   class  DocumentCommand
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    Document _document;
InBlock.gif
InBlock.gif    
public DocumentCommand(Document doc)
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
this._document = doc;
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif
InBlock.gif    
/// 执行
InBlock.gif
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif
InBlock.gif    
public abstract void Execute();
InBlock.gif
ExpandedBlockEnd.gif}

其他的具体命令类都继承于该抽象类,如下:


5

示意性代码:

ExpandedBlockStart.gif ContractedBlock.gif /**/ /// <summary>
InBlock.gif
InBlock.gif
/// 显示命令
InBlock.gif
ExpandedBlockEnd.gif
/// </summary>
None.gif
None.gif
public   class  DisplayCommand : DocumentCommand
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
public DisplayCommand(Document doc)
InBlock.gif
InBlock.gif        : 
base(doc)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{    
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public override void Execute()
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        _document.Display();   
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
None.gif
ExpandedBlockStart.gifContractedBlock.gif
/**/ /// <summary>
InBlock.gif
InBlock.gif
/// 撤销命令
InBlock.gif
ExpandedBlockEnd.gif
/// </summary>

None.gif
None.gif
public   class  UndoCommand : DocumentCommand
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif
InBlock.gif    
public UndoCommand(Document doc)
InBlock.gif
InBlock.gif        : 
base(doc)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{   
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public override void Execute()
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        _document.Undo();   
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
None.gif
ExpandedBlockStart.gifContractedBlock.gif
/**/ /// <summary>
InBlock.gif
InBlock.gif
/// 重做命令
InBlock.gif
ExpandedBlockEnd.gif
/// </summary>

None.gif
None.gif
public   class  RedoCommand : DocumentCommand
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
public RedoCommand(Document doc)
InBlock.gif
InBlock.gif        : 
base(doc)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public override void Execute()
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        _document.Redo();   
ExpandedSubBlockEnd.gif    }
 
ExpandedBlockEnd.gif}

现在还需要一个Invoker角色的类,这其实相当于一个中间角色,前面我曾经说过,使用这样的一个中间层也是我们经常使用的手法,即把AB的依赖转换为AC的依赖。如下:

6

示意性代码:

ExpandedBlockStart.gif ContractedBlock.gif /**/ /// <summary>
InBlock.gif
InBlock.gif
/// Invoker角色
InBlock.gif
ExpandedBlockEnd.gif
/// </summary>

None.gif
None.gif
public   class  DocumentInvoker
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    DocumentCommand _discmd;
InBlock.gif
InBlock.gif    DocumentCommand _undcmd;
InBlock.gif
InBlock.gif    DocumentCommand _redcmd;
InBlock.gif
InBlock.gif    
public DocumentInvoker(DocumentCommand discmd,DocumentCommand undcmd,DocumentCommand redcmd)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
InBlock.gif        
this._discmd = discmd;
InBlock.gif
InBlock.gif        
this._undcmd = undcmd;
InBlock.gif
InBlock.gif        
this._redcmd = redcmd;
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public void Display()
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        _discmd.Execute();
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public void Undo()
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        _undcmd.Execute();
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public void Redo()
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        _redcmd.Execute();
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

现在再来看客户程序的调用代码:

None.gif class  Program
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
static void Main(string[] args)
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
InBlock.gif        Document doc 
= new Document();
InBlock.gif
InBlock.gif
InBlock.gif        DocumentCommand discmd 
= new DisplayCommand(doc);
InBlock.gif
InBlock.gif        DocumentCommand undcmd 
= new UndoCommand(doc);
InBlock.gif
InBlock.gif        DocumentCommand redcmd 
= new RedoCommand(doc);
InBlock.gif
InBlock.gif
InBlock.gif        DocumentInvoker invoker 
= new DocumentInvoker(discmd,undcmd,redcmd);
InBlock.gif
InBlock.gif        invoker.Display();
InBlock.gif
InBlock.gif        invoker.Undo();
InBlock.gif
InBlock.gif        invoker.Redo();
InBlock.gif
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

可以看到:

1.在客户程序中,不再依赖于DocumentDisplay()Undo()Redo()命令,通过Command对这些命令进行了封装,使用它的一个关键就是抽象的Command类,它定义了一个操作的接口。同时我们也可以看到,本来这三个命令仅仅是三个方法而已,但是通过Command模式却把它们提到了类的层面,这其实是违背了面向对象的原则,但它却优雅的解决了分离命令的请求者和命令的执行者的问题,在使用Command模式的时候,一定要判断好使用它的时机。

2.上面的Undo/Redo只是简单示意性的实现,如果要实现这样的效果,需要对命令对象设置一个状态,由命令对象可以把状态存储起来。

.NET中的Command模式

ASP.NETMVC模式中,有一种叫Front Controller的模式,它分为HandlerCommand树两个部分,Handler处理所有公共的逻辑,接收HTTP PostGet请求以及相关的参数并根据输入的参数选择正确的命令对象,然后将控制权传递到Command对象,由其完成后面的操作,这里面其实就是用到了Command模式。

7  Front Controller 的处理程序部分结构图

8 Front Controller的命令部分结构图

Handler 类负责处理各个 Web 请求,并将确定正确的 Command 对象这一职责委派给 CommandFactory 类。当 CommandFactory 返回 Command 对象后,Handler 将调用 Command 上的 Execute 方法来执行请求。具体的实现如下

Handler类:

ExpandedBlockStart.gif ContractedBlock.gif /**/ /// <summary>
InBlock.gif
InBlock.gif
/// Handler类
InBlock.gif
ExpandedBlockEnd.gif
/// </summary>

None.gif
None.gif
public   class  Handler : IHttpHandler
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
public void ProcessRequest(HttpContext context)
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
InBlock.gif        Command command 
= CommandFactory.Make(context.Request.Params);
InBlock.gif
InBlock.gif        command.Execute(context);
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public bool IsReusable
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
get
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return true;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

Command接口:

ExpandedBlockStart.gif ContractedBlock.gif /**/ /// <summary>
InBlock.gif
InBlock.gif
/// Command
InBlock.gif
ExpandedBlockEnd.gif
/// </summary>

None.gif
None.gif
public   interface  Command
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
void Execute(HttpContext context);
ExpandedBlockEnd.gif}

CommandFactory类:

ExpandedBlockStart.gif ContractedBlock.gif /**/ /// <summary>
InBlock.gif
InBlock.gif
/// CommandFactory
InBlock.gif
ExpandedBlockEnd.gif
/// </summary>

None.gif
None.gif
public   class  CommandFactory
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
public static Command Make(NameValueCollection parms)
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
InBlock.gif        
string requestParm = parms["requestParm"];
InBlock.gif
InBlock.gif        Command command 
= null;
InBlock.gif
InBlock.gif        
//根据输入参数得到不同的Command对象
InBlock.gif

InBlock.gif        
switch (requestParm)
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
case "1":
InBlock.gif
InBlock.gif                command 
= new FirstPortal();
InBlock.gif
InBlock.gif                
break;
InBlock.gif
InBlock.gif            
case "2":
InBlock.gif
InBlock.gif                command 
= new SecondPortal();
InBlock.gif
InBlock.gif                
break;
InBlock.gif
InBlock.gif            
default:
InBlock.gif
InBlock.gif                command 
= new FirstPortal();
InBlock.gif
InBlock.gif                
break;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
return command;
InBlock.gif
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

RedirectCommand类:

None.gif public   abstract   class  RedirectCommand : Command
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
//获得Web.Config中定义的key和url键值对,UrlMap类详见下载包中的代码
InBlock.gif

InBlock.gif    
private UrlMap map = UrlMap.SoleInstance;
InBlock.gif
InBlock.gif    
protected abstract void OnExecute(HttpContext context);
InBlock.gif
InBlock.gif    
public void Execute(HttpContext context)
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        OnExecute(context);
InBlock.gif
InBlock.gif        
//根据key和url键值对提交到具体处理的页面
InBlock.gif

InBlock.gif        
string url = String.Format("{0}?{1}", map.Map[context.Request.Url.AbsolutePath], context.Request.Url.Query);
InBlock.gif
InBlock.gif        context.Server.Transfer(url);
InBlock.gif
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

FirstPortal类:

None.gif public   class  FirstPortal : RedirectCommand
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
protected override void OnExecute(HttpContext context)
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
//在输入参数中加入项portalId以便页面处理
InBlock.gif

InBlock.gif        context.Items[
"portalId"= "1";
InBlock.gif
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

SecondPortal类:

None.gif public   class  SecondPortal : RedirectCommand
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
protected override void OnExecute(HttpContext context)
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        context.Items[
"portalId"= "2";
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

效果及实现要点

1Command模式的根本目的在于将“行为请求者”与“行为实现者”解耦,在面向对象语言中,常见的实现手段是“将行为抽象为对象”。

2.实现Command接口的具体命令对象ConcreteCommand有时候根据需要可能会保存一些额外的状态信息。

3.通过使用Compmosite模式,可以将多个命令封装为一个“复合命令”MacroCommand

4Command模式与C#中的Delegate有些类似。但两者定义行为接口的规范有所区别:Command以面向对象中的“接口-实现”来定义行为接口规范,更严格,更符合抽象原则;Delegate以函数签名来定义行为接口规范,更灵活,但抽象能力比较弱。

5.使用命令模式会导致某些系统有过多的具体命令类。某些系统可能需要几十个,几百个甚至几千个具体命令类,这会使命令模式在这样的系统里变得不实际。

适用性

在下面的情况下应当考虑使用命令模式:

1.使用命令模式作为"CallBack"在面向对象系统中的替代。"CallBack"讲的便是先将一个函数登记上,然后在以后调用此函数。

2.需要在不同的时间指定请求、将请求排队。一个命令对象和原先的请求发出者可以有不同的生命期。换言之,原先的请求发出者可能已经不在了,而命令对象本身仍然是活动的。这时命令的接收者可以是在本地,也可以在网络的另外一个地址。命令对象可以在串形化之后传送到另外一台机器上去。

3.系统需要支持命令的撤消(undo)。命令对象可以把状态存储起来,等到客户端需要撤销命令所产生的效果时,可以调用undo()方法,把命令所产生的效果撤销掉。命令对象还可以提供redo()方法,以供客户端在需要时,再重新实施命令效果。

4.如果一个系统要将系统中所有的数据更新到日志里,以便在系统崩溃时,可以根据日志里读回所有的数据更新命令,重新调用Execute()方法一条一条执行这些命令,从而恢复系统在崩溃前所做的数据更新。

总结

Command模式是非常简单而又优雅的一种设计模式,它的根本目的在于将“行为请求者”与“行为实现者”解耦。

更多的设计模式文章可以访问《.NET设计模式系列文章

 

参考资料

Erich Gamma等,《设计模式:可复用面向对象软件的基础》,机械工业出版社

Robert C.Martin,《敏捷软件开发:原则、模式与实践》,清华大学出版社

阎宏,《Java与模式》,电子工业出版社

Alan Shalloway James R. Trott,《Design Patterns Explained》,中国电力出版社

MSDN WebCast C#面向对象设计模式纵横谈(14)Command命令模式(结构型模式)

袁剑,《领悟Web设计模式》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值