二、責任鏈模式的結構
責任鏈模式涉及到的角色如下所示:
抽象處理者(Handler)角色:定義出一個處理請求的接口。如果需要,接口可以定義出一個方法,以設定和返回對下家的引用。這個角色通常由一個抽象類或接口實現。---www.bianceng.cn
具體處理者(ConcreteHandler)角色:具體處理者接到請求後,可以選擇將請求處理掉,或者將請求傳給下家。由於具體處理者持有對下家的引用,因此,如果需要,具體處理者可以訪問下家。
三、責任鏈模式的示意性源代碼
// Chain of Responsibility pattern -- Structural example
using System;
// "Handler"
abstract class Handler
{
// FIElds
protected Handler successor;
// Methods
public void SetSuccessor( Handler successor )
{
this.successor = successor;
}
abstract public void HandleRequest( int request );
}
// "ConcreteHandler1"
class ConcreteHandler1 : Handler
{
// Methods
override public void HandleRequest( int request )
{
if( request >= 0 && request < 10 )
Console.WriteLine("{0} handled request {1}",
this, request );
else
if( successor != null )
successor.HandleRequest( request );
}
}
// "ConcreteHandler2"
class ConcreteHandler2 : Handler
{
// Methods
override public void HandleRequest( int request )
{
if( request >= 10 && request < 20 )
Console.WriteLine("{0} handled request {1}",
this, request );
else
if( successor != null )
successor.HandleRequest( request );
}
}
// "ConcreteHandler3"
class ConcreteHandler3 : Handler
{
// Methods
override public void HandleRequest( int request )
{
if( request >= 20 && request < 30 )
Console.WriteLine("{0} handled request {1}",
this, request );
else
if( successor != null )
successor.HandleRequest( request );
}
}
/**//// <summary>
/// ClIEnt test
/// </summary>
public class ClIEnt
{
public static void Main( string[] args )
{
// Setup Chain of Responsibility
Handler h1 = new ConcreteHandler1();
Handler h2 = new ConcreteHandler2();
Handler h3 = new ConcreteHandler3();
h1.SetSuccessor(h2);
h2.SetSuccessor(h3);
// Generate and process request
int[] requests = { 2, 5, 14, 22, 18, 3, 27, 20 };
foreach( int request in requests )
h1.HandleRequest( request );
}
}