Chinaunix首页 | 论坛 | 博客
  • 博客访问: 657845
  • 博文数量: 220
  • 博客积分: 10487
  • 博客等级: 上将
  • 技术积分: 2072
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-09 00:25
文章分类

全部博文(220)

文章存档

2012年(5)

2011年(38)

2010年(135)

2009年(42)

我的朋友

分类:

2009-10-18 20:34:34

定义

将请求封装成对象,这样可以参数化各种各样来自客户端的请求,如排队或日志请求,也包括可逆的操作。

使用频度: 中高


UML 类图



参与者

该模式参与的类或对象

  • Command(命令)
    • 定义执行操作的接口
  • ConcreteCommand(具体命令)
    • 绑定Receiver对象和action
    • 通过调用reveiver的相应操作实现Excute方法
  • Client(客户端,命令应用)
    • 创建Concrete对象并设置其receiver
  • Invoker(调用者,使用者)
    • 让命令执行请求
  • Receiver(接收者)
    • 执行与请求相应的操作

 
C# 示例代码


// Command pattern -- Structural example


using System;

 

namespace DoFactory.GangOfFour.Command.Structural

{

  ///




  /// MainApp startup class for Structural


  /// Command Design Pattern.


  ///



  class MainApp

  {

    ///


    /// Entry point into console application.


    ///



    static void Main()

    {

      // Create receiver, command, and invoker


      Receiver receiver = new Receiver();

      Command command = new ConcreteCommand(receiver);

      Invoker invoker = new Invoker();

 

      // Set and execute command


      invoker.SetCommand(command);

      invoker.ExecuteCommand();

 

      // Wait for user


      Console.ReadKey();

    }

  }

 

  ///


  /// The 'Command' abstract class


  ///



  abstract class Command

  {

    protected Receiver receiver;

 

    // Constructor


    public Command(Receiver receiver)

    {

      this.receiver = receiver;

    }

 

    public abstract void Execute();

  }

 

  ///


  /// The 'ConcreteCommand' class


  ///



  class ConcreteCommand : Command

  {

    // Constructor


    public ConcreteCommand(Receiver receiver) :

      base(receiver)

    {

    }

 

    public override void Execute()

    {

      receiver.Action();

    }

  }

 

  ///


  /// The 'Receiver' class


  ///



  class Receiver

  {

    public void Action()

    {

      Console.WriteLine("Called Receiver.Action()");

    }

  }

 

  ///


  /// The 'Invoker' class


  ///



  class Invoker

  {

    private Command _command;

 

    public void SetCommand(Command command)

    {

      this._command = command;

    }

 

    public void ExecuteCommand()

    {

      _command.Execute();

    }

  }

}


输出

Called Receiver.Action()


阅读(880) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~