设计模式-Chain of Responsibility Pattern

行为模式(Behavioral Pattern)是对在不同的对象之间划分责任和算法的抽象化。行为模式不仅仅是关于类和对象的,而且是关于它们之间的相互作用的。

行为模式分为类的行为模式和对象的行为模式两种。

  • 类的行为模式:类的行为模式使用继承关系在几个类之问分配行为。
  • 对象的行为模式:对象的行为模式则使用对象的聚合来分配行为。

在后面将要介绍的行为模式包括以下几种:

  • Chain of Resp.(责任链模式)A way of passing a request between a chain of objects
  • Command(命令模式)Encapsulate a command request as an object
  • Interpreter(解释器模式)A way to include language elements in a program
  • Iterator(迭代子模式)Sequentially access the elements of a collection
  • Mediator(中介者模式)Defines simplified communication between classes
  • Memento(备忘录模式)Capture and restore an object's internal state
  • Observer(观察者模式)A way of notifying change to a number of classes
  • State(状态模式)Alter an object's behavior when its state changes
  • Strategy(策略模式)Encapsulates an algorithm inside a class
  • Template Method(模版方法模式)Defer the exact steps of an algorithm to a subclass
  • Visitor(访问者模式)Defines a new operation to a class without change

 

一、 职责链(Chain of Responsibility)模式

责 任链模式是一种对象的行为模式【GOF95】。在责任链模式里,很多对象由每一个对象对其下家的引用而连接起来形成一条链。请求在这个链上传递,直到链上 的某一个对象决定处理此请求。发出这个请求的客户端并不知道链上的哪一个对象最终处理这个请求,这使得系统可以在不影响客户端的情况下动态地重新组织链和 分配责任。

从击鼓传花谈起

击鼓传花是一种热闹而又紧张的饮酒游戏。在酒宴上宾客依次坐定位置,由一人击鼓,击鼓的地方与传花的地方是分开的,以示公正。开始击鼓时,花束就开始依次传递,鼓声一落,如果花束在某人手中,则该人就得饮酒。

击鼓传花便是责任链模式的应用。责任链可能是一条直线、一个环链或者一个树结构的一部分。


二、 责任链模式的结构

 

责任链模式涉及到的角色如下所示:

Pic98.gif

抽象处理者(Handler)角色:定义出一个处理请求的接口。如果需要,接口可以定义出一个方法,以设定和返回对下家的引用。这个角色通常由一个抽象类或接口实现。

具体处理者(ConcreteHandler)角色:具体处理者接到请求后,可以选择将请求处理掉,或者将请求传给下家。由于具体处理者持有对下家的引用,因此,如果需要,具体处理者可以访问下家。


三、 责任链模式的示意性源代码

None.gif //  Chain of Responsibility pattern -- Structural example  
None.gif
using  System;
None.gif
None.gif
//  "Handler"
None.gif
abstract   class  Handler
ExpandedBlockStart.gif
{
InBlock.gif  
// Fields
InBlock.gif
  protected Handler successor;
InBlock.gif 
InBlock.gif  
// Methods
InBlock.gif
  public void SetSuccessor( Handler successor )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
this.successor = successor;
ExpandedSubBlockEnd.gif  }

InBlock.gif  
abstract public void HandleRequest( int request );
ExpandedBlockEnd.gif}

None.gif
None.gif
//  "ConcreteHandler1"
None.gif
class  ConcreteHandler1 : Handler
ExpandedBlockStart.gif
{
InBlock.gif  
// Methods
InBlock.gif
  override public void HandleRequest( int request )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
if( request >= 0 && request < 10 )
InBlock.gif      Console.WriteLine(
"{0} handled request {1}",
InBlock.gif        
this, request );
InBlock.gif    
else
InBlock.gif      
if( successor != null )
InBlock.gif      successor.HandleRequest( request );
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

None.gif
None.gif
//  "ConcreteHandler2"
None.gif
class  ConcreteHandler2 : Handler
ExpandedBlockStart.gif
{
InBlock.gif  
// Methods
InBlock.gif
  override public void HandleRequest( int request )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
if( request >= 10 && request < 20 )
InBlock.gif      Console.WriteLine(
"{0} handled request {1}",
InBlock.gif        
this, request );
InBlock.gif    
else
InBlock.gif      
if( successor != null )
InBlock.gif      successor.HandleRequest( request );
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

None.gif
None.gif
//  "ConcreteHandler3"
None.gif
class  ConcreteHandler3 : Handler
ExpandedBlockStart.gif
{
InBlock.gif  
// Methods
InBlock.gif
  override public void HandleRequest( int request )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
if( request >= 20 && request < 30 )
InBlock.gif      Console.WriteLine(
"{0} handled request {1}",
InBlock.gif        
this, request );
InBlock.gif    
else
InBlock.gif      
if( successor != null )
InBlock.gif      successor.HandleRequest( request );
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

None.gif
ExpandedBlockStart.gif
/// <summary>
InBlock.gif
/// Client test
ExpandedBlockEnd.gif
/// </summary>
None.gif public   class  Client
ExpandedBlockStart.gif
{
InBlock.gif  
public static void Main( string[] args )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
// Setup Chain of Responsibility
InBlock.gif
    Handler h1 = new ConcreteHandler1();
InBlock.gif    Handler h2 
= new ConcreteHandler2();
InBlock.gif    Handler h3 
= new ConcreteHandler3();
InBlock.gif    h1.SetSuccessor(h2);
InBlock.gif    h2.SetSuccessor(h3);
InBlock.gif
InBlock.gif    
// Generate and process request
ExpandedSubBlockStart.gif
    int[] requests = 2514221832720 };
InBlock.gif
InBlock.gif    
foreachint request in requests )
InBlock.gif      h1.HandleRequest( request );
InBlock.gif
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

 


四、 纯的与不纯的责任链模式

一个纯的责任链模式要求一个具体的处理者对象只能在两个行为中选择一个:一个是承担责任,二是把责任推给下家。不允许出现某一个具体处理者对象在承担了一部分责任后又把责任向下传的情况。

在一个纯的责任链模式里面,一个请求必须被某一个处理者对象所接收;在一个不纯的责任链模式里面,一个请求可以最终不被任何接收端对象所接收。纯的责任链模式的例子是不容易找到的,一般看到的例子均是不纯的责任链模式的实现。


五、 责任链模式的实际应用案例

下面的责任链模式代码演示了不同职务的人根据所设定的权限对一个购买请求作出决策或将其交给更高的决策者。

None.gif //  Chain of Responsibility pattern -- Real World example  
None.gif
using  System;
None.gif
None.gif
//  "Handler"
None.gif
abstract   class  Approver
ExpandedBlockStart.gif
{
InBlock.gif  
// Fields
InBlock.gif
  protected string name;
InBlock.gif  
protected Approver successor;
InBlock.gif
InBlock.gif  
// Constructors
InBlock.gif
  public Approver( string name )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
this.name = name;
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
// Methods
InBlock.gif
  public void SetSuccessor( Approver successor )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
this.successor = successor;
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
abstract public void ProcessRequest( PurchaseRequest request );
ExpandedBlockEnd.gif}

None.gif
None.gif
//  "ConcreteHandler"
None.gif
class  Director : Approver
ExpandedBlockStart.gif
{
InBlock.gif  
// Constructors
ExpandedSubBlockStart.gif
  public Director ( string name ) : base( name ) {}
InBlock.gif
InBlock.gif  
// Methods
InBlock.gif
  override public void ProcessRequest( PurchaseRequest request )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
if( request.Amount < 10000.0 )
InBlock.gif      Console.WriteLine( 
"{0} {1} approved request# {2}",
InBlock.gif        
this, name, request.Number);
InBlock.gif    
else
InBlock.gif      
if( successor != null )
InBlock.gif      successor.ProcessRequest( request );
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

None.gif
None.gif
//  "ConcreteHandler"
None.gif
class  VicePresident : Approver
ExpandedBlockStart.gif
{
InBlock.gif  
// Constructors
ExpandedSubBlockStart.gif
  public VicePresident ( string name ) : base( name ) {}
InBlock.gif
InBlock.gif  
// Methods
InBlock.gif
  override public void ProcessRequest( PurchaseRequest request )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
if( request.Amount < 25000.0 )
InBlock.gif      Console.WriteLine( 
"{0} {1} approved request# {2}",
InBlock.gif        
this, name, request.Number);
InBlock.gif    
else
InBlock.gif      
if( successor != null )
InBlock.gif      successor.ProcessRequest( request );
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

None.gif
None.gif
//  "ConcreteHandler"
None.gif
class  President : Approver
ExpandedBlockStart.gif
{
InBlock.gif  
// Constructors
ExpandedSubBlockStart.gif
  public President ( string name ) : base( name ) {}
InBlock.gif  
// Methods
InBlock.gif
  override public void ProcessRequest( PurchaseRequest request )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
if( request.Amount < 100000.0 )
InBlock.gif      Console.WriteLine( 
"{0} {1} approved request# {2}",
InBlock.gif        
this, name, request.Number);
InBlock.gif    
else
InBlock.gif      Console.WriteLine( 
"Request# {0} requires " +
InBlock.gif        
"an executive meeting!", request.Number );
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

None.gif
None.gif
//  Request details
None.gif
class  PurchaseRequest
ExpandedBlockStart.gif
{
InBlock.gif  
// Member Fields
InBlock.gif
  private int number;
InBlock.gif  
private double amount;
InBlock.gif  
private string purpose;
InBlock.gif
InBlock.gif  
// Constructors
InBlock.gif
  public PurchaseRequest( int number,  
InBlock.gif    
double amount, string purpose )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
this.number = number;
InBlock.gif    
this.amount = amount;
InBlock.gif    
this.purpose = purpose;
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
// Properties
InBlock.gif
  public double Amount
ExpandedSubBlockStart.gif  
{
ExpandedSubBlockStart.gif    
getreturn amount; }
ExpandedSubBlockStart.gif    
set{ amount = value; }
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
public string Purpose
ExpandedSubBlockStart.gif  
{
ExpandedSubBlockStart.gif    
getreturn purpose; }
ExpandedSubBlockStart.gif    
set{ purpose = value; }
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
public int Number
ExpandedSubBlockStart.gif  
{
ExpandedSubBlockStart.gif    
getreturn number; }
ExpandedSubBlockStart.gif    
set{ number = value; }
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

None.gif
ExpandedBlockStart.gif
/// <summary>
InBlock.gif
///  ChainApp Application
ExpandedBlockEnd.gif
/// </summary>
None.gif public   class  ChainApp
ExpandedBlockStart.gif
{
InBlock.gif  
public static void Main( string[] args )
ExpandedSubBlockStart.gif  
{
InBlock.gif    
// Setup Chain of Responsibility
InBlock.gif
    Director Larry = new Director( "Larry" );
InBlock.gif    VicePresident Sam 
= new VicePresident( "Sam" );
InBlock.gif    President Tammy 
= new President( "Tammy" );
InBlock.gif    Larry.SetSuccessor( Sam );
InBlock.gif    Sam.SetSuccessor( Tammy );
InBlock.gif
InBlock.gif    
// Generate and process different requests
InBlock.gif
    PurchaseRequest rs = new PurchaseRequest( 2034350.00"Supplies" );
InBlock.gif    Larry.ProcessRequest( rs );
InBlock.gif
InBlock.gif    PurchaseRequest rx 
= new PurchaseRequest( 203532590.10"Project X" );
InBlock.gif    Larry.ProcessRequest( rx );
InBlock.gif
InBlock.gif    PurchaseRequest ry 
= new PurchaseRequest( 2036122100.00"Project Y" );
InBlock.gif    Larry.ProcessRequest( ry );
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

 

六、 责任链模式的实现

责任链模式并不创建责任链。责任链的创建必须由系统的其它部分创建出来。

责任链模式降低了请求的发送端和接收端之间的耦合,使多个对象都有机会处理这个请求。一个链可以是一条线,一个树,也可以是一个环。如下图所示,责任链是一个树结构的一部分。

 Pic99.gif

参考文献:
阎宏,《Java与模式》,电子工业出版社
[美]James W. Cooper,《C#设计模式》,电子工业出版社
[美]Alan Shalloway  James R. Trott,《Design Patterns Explained》,中国电力出版社
[美]Robert C. Martin,《敏捷软件开发-原则、模式与实践》,清华大学出版社
[美]Don Box, Chris Sells,《.NET本质论 第1卷:公共语言运行库》,中国电力出版社

转载于:https://my.oschina.net/qihh/blog/57808

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值