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

简介:


命令模式(Command Pattern

——.NET设计模式系列之十七
TerryLee 20067
概述
在软件系统中,“行为请求者”与“行为实现者”通常呈现一种“紧耦合”。但在某些场合,比如要对行为进行“记录、撤销/重做、事务”等处理,这种无法抵御变化的紧耦合是不合适的。在这种情况下,如何将“行为请求者”与“行为实现者”解耦?将一组行为抽象为对象,可以实现二者之间的松耦合[李建忠]。这就是本文要说的Command模式。
意图
将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤消的操作。[GOF 《设计模式》]
结构图
Command 模式结构图如下:
 Command模式结构图
生活中的例子
Command 模式将一个请求封装为一个对象,从而使你可以使用不同的请求对客户进行参数化。用餐时的账单是Command模式的一个例子。服务员接受顾客的点单,把它记在账单上封装。这个点单被排队等待烹饪。注意这里的"账单"是不依赖于菜单的,它可以被不同的顾客使用,因此它可以添入不同的点单项目。
 使用用餐例子的Command模式对象图
Command 模式解说
在众多的设计模式中,Command模式是很简单也很优雅的一种设计模式。Command模式它封装的是命令,把命令发出者的责任和命令执行者的责任分开。我们知道,一个类是一组操作和相应的一些变量的集合,现在有这样一个类 Document ,如下:
3
示意性代码:
ExpandedBlockStart.gif /// <summary>
InBlock.gif
InBlock.gif
/// 文档类
InBlock.gif
ExpandedBlockEnd.gif
/// </summary>

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

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

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

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

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

ExpandedBlockEnd.gif}
一般情况下我们使用这个类的时候,都会这样去写:
None.gif class  Program
None.gif
ExpandedBlockStart.gif
{
InBlock.gif    
static void Main(string[] args)
InBlock.gif
ExpandedSubBlockStart.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 /// <summary>
InBlock.gif
InBlock.gif
/// 抽象命令
InBlock.gif
ExpandedBlockEnd.gif
/// </summary>

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

InBlock.gif
ExpandedSubBlockStart.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 /// <summary>
InBlock.gif
InBlock.gif
/// 显示命令
InBlock.gif
ExpandedBlockEnd.gif
/// </summary>

None.gif
None.gif
public   class  DisplayCommand : DocumentCommand
None.gif
ExpandedBlockStart.gif
{
InBlock.gif    
public DisplayCommand(Document doc)
InBlock.gif
InBlock.gif        : 
base(doc)
ExpandedSubBlockStart.gif    
{    
InBlock.gif
ExpandedSubBlockEnd.gif    }

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

ExpandedBlockEnd.gif}

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

None.gif
None.gif
public   class  UndoCommand : DocumentCommand
None.gif
ExpandedBlockStart.gif

InBlock.gif    
public UndoCommand(Document doc)
InBlock.gif
InBlock.gif        : 
base(doc)
ExpandedSubBlockStart.gif    
{   
InBlock.gif
ExpandedSubBlockEnd.gif    }

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

ExpandedBlockEnd.gif}

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

None.gif
None.gif
public   class  RedoCommand : DocumentCommand
None.gif
ExpandedBlockStart.gif
{
InBlock.gif    
public RedoCommand(Document doc)
InBlock.gif
InBlock.gif        : 
base(doc)
ExpandedSubBlockStart.gif    

InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public override void Execute()
InBlock.gif
ExpandedSubBlockStart.gif    
{
InBlock.gif        _document.Redo();   
ExpandedSubBlockEnd.gif    }
 
ExpandedBlockEnd.gif}
现在还需要一个 Invoker角色的类,这其实相当于一个中间角色,前面我曾经说过,使用这样的一个中间层也是我们经常使用的手法,即把 AB的依赖转换为 AC的依赖。如下:
6
示意性代码:
ExpandedBlockStart.gif /// <summary>
InBlock.gif
InBlock.gif
/// Invoker角色
InBlock.gif
ExpandedBlockEnd.gif
/// </summary>

None.gif
None.gif
public   class  DocumentInvoker
None.gif
ExpandedBlockStart.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.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.gif    
{
InBlock.gif        _discmd.Execute();
ExpandedSubBlockEnd.gif    }

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

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

ExpandedBlockEnd.gif}
现在再来看客户程序的调用代码:
None.gif class  Program
None.gif
ExpandedBlockStart.gif
{
InBlock.gif    
static void Main(string[] args)
InBlock.gif
ExpandedSubBlockStart.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 /// <summary>
InBlock.gif
InBlock.gif
/// Handler类
InBlock.gif
ExpandedBlockEnd.gif
/// </summary>

None.gif
None.gif
public   class  Handler : IHttpHandler
None.gif
ExpandedBlockStart.gif
{
InBlock.gif    
public void ProcessRequest(HttpContext context)
InBlock.gif
ExpandedSubBlockStart.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.gif    
{
InBlock.gif        
get
InBlock.gif
ExpandedSubBlockStart.gif        
{
InBlock.gif            
return true;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}
Command 接口:
ExpandedBlockStart.gif /// <summary>
InBlock.gif
InBlock.gif
/// Command
InBlock.gif
ExpandedBlockEnd.gif
/// </summary>

None.gif
None.gif
public   interface  Command
None.gif
ExpandedBlockStart.gif
{
InBlock.gif    
void Execute(HttpContext context);
ExpandedBlockEnd.gif}
CommandFactory 类:
ExpandedBlockStart.gif /// <summary>
InBlock.gif
InBlock.gif
/// CommandFactory
InBlock.gif
ExpandedBlockEnd.gif
/// </summary>

None.gif
None.gif
public   class  CommandFactory
None.gif
ExpandedBlockStart.gif
{
InBlock.gif    
public static Command Make(NameValueCollection parms)
InBlock.gif
ExpandedSubBlockStart.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.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.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.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.gif
{
InBlock.gif    
protected override void OnExecute(HttpContext context)
InBlock.gif
ExpandedSubBlockStart.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.gif
{
InBlock.gif    
protected override void OnExecute(HttpContext context)
InBlock.gif
ExpandedSubBlockStart.gif    
{
InBlock.gif        context.Items[
"portalId"= "2";
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}
效果及实现要点
1 Command模式的根本目的在于将“行为请求者”与“行为实现者”解耦,在面向对象语言中,常见的实现手段是“将行为抽象为对象”。
2 .实现Command接口的具体命令对象ConcreteCommand有时候根据需要可能会保存一些额外的状态信息。
3 .通过使用Compmosite模式,可以将多个命令封装为一个“复合命令”MacroCommand
4 Command模式与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设计模式》










本文转自lihuijun51CTO博客,原文链接: http://blog.51cto.com/terrylee/67767  ,如需转载请自行联系原作者

相关文章
|
3月前
|
设计模式 算法 Java
行为型设计模式-策略模式(Strategy Pattern)
行为型设计模式-策略模式(Strategy Pattern)
|
3月前
|
设计模式 算法
设计模式 - 行为型模式_ 访问者模式Visitor Pattern
设计模式 - 行为型模式_ 访问者模式Visitor Pattern
39 1
设计模式 - 行为型模式_ 访问者模式Visitor Pattern
|
5天前
|
设计模式 存储 Java
Java设计模式:解释一下单例模式(Singleton Pattern)。
`Singleton Pattern`是Java中的创建型设计模式,确保类只有一个实例并提供全局访问点。它通过私有化构造函数,用静态方法返回唯一的实例。类内静态变量存储此实例,对外仅通过静态方法访问。
12 1
|
11天前
|
设计模式 Java
23种设计模式,命令模式的概念优缺点以及JAVA代码举例
【4月更文挑战第7天】命令模式是一种行为设计模式,它将请求或简单操作封装为一个对象。这种模式允许用户通过调用对象来参数化其他对象的方法,并能保存、排队和执行方法调用。
16 1
|
1月前
|
设计模式 存储 Java
【设计模式】命令模式
【设计模式】命令模式
|
3月前
|
设计模式 Java
设计模式-命令模式
设计模式-命令模式
33 1
|
3月前
|
设计模式 Java
设计模式-命令模式(Command)
设计模式-命令模式(Command)
32 0
|
3月前
|
设计模式 存储 Java
Java设计模式-命令模式
命令(Command)模式是指将请求封装成为一个对象,使发出请求和执行请求的责任分割开,方便将命令对象进行存储、传递、调用、增加与管理。 也就是将发送者、接收者和调用命令封装成独立的对象,来供客户端调用。属于行为模式的一种。
29 1
Java设计模式-命令模式
|
3月前
|
设计模式 Go 开发工具
Golang设计模式——06命令模式
Golang设计模式——06命令模式
20 0
|
3月前
|
设计模式 存储 前端开发
【设计模式】之命令模式
命令模式是一种非常有用的设计模式,在前端开发中经常用于管理和执行操作。它通过将操作封装成对象,并将其作为参数传递、存储或记录,实现了优雅地管理和执行操作。通过使用命令模式,我们可以提高代码的可维护性和可扩展性。然而,在应用命令模式时需要权衡其带来的优缺点,并根据具体情况进行选择。
39 0