-
責任鏈模式
鎖定
責任鏈模式是一種設計模式。在責任鏈模式裏,很多對象由每一個對象對其下家的引用而連接起來形成一條鏈。請求在這個鏈上傳遞,直到鏈上的某一個對象決定處理此請求。發出這個請求的客户端並不知道鏈上的哪一個對象最終處理這個請求,這使得系統可以在不影響客户端的情況下動態地重新組織和分配責任。
- 中文名
- 責任鏈模式
- 外文名
- Chain of Responsibility
- 性 質
- 一種設計模式
- 學 科
- 計算機
責任鏈模式簡介
責任鏈模式在面向對象程式設計裏是一種軟件設計模式,它包含了一些命令對象和一系列的處理對象。每一個處理對象決定它能處理哪些命令對象,它也知道如何將它不能處理的命令對象傳遞給該鏈中的下一個處理對象。該模式還描述了往該處理鏈的末尾添加新的處理對象的方法。
[1]
責任鏈模式角色
責任鏈模式涉及到的角色如下所示:
● 抽象處理者(Handler)角色:定義出一個處理請求的接口。如果需要,接口可以定義 出一個方法以設定和返回對下家的引用。這個角色通常由一個Java抽象類或者Java接口實現。Handler類的聚合關係給出了具體子類對下家的引用,抽象方法handleRequest()規範了子類處理請求的操作。
責任鏈模式Java代碼示例
以下的日誌類(logging)例子演示了該模式。 每一個logging handler首先決定是否需要在該層做處理,然後將控制傳遞到下一個logging handler。程序的輸出是:
Writing to debug output: Entering function y. Writing to debug output: Step1 completed. Sending via e-mail: Step1 completed. Writing to debug output: An error has occurred. Sending via e-mail: An error has occurred. Writing to stderr: An error has occurred.
注意:該例子不是日誌類的推薦實現方式。
同時,需要注意的是,通常在責任鏈模式的實現中,如果在某一層已經處理了這個logger,那麼這個logger就不會傳遞下去。在我們這個例子中,消息會一直傳遞到最底層不管它是否已經被處理。
import java.util.*;abstract class Logger { public static int ERR = 3; public static int NOTICE = 5; public static int DEBUG = 7; protected int mask; // The next element in the chain of responsibility protected Logger next; public Logger setNext( Logger l) { next = l; return this; } public final void message( String msg, int priority ) { if ( priority <= mask ) { writeMessage( msg ); if ( next != null ) { next.message( msg, priority ); } } } protected abstract void writeMessage( String msg );} class StdoutLogger extends Logger { public StdoutLogger( int mask ) { this.mask = mask; } protected void writeMessage( String msg ) { System.out.println( "Writting to stdout: " + msg ); }}class EmailLogger extends Logger { public EmailLogger( int mask ) { this.mask = mask; } protected void writeMessage( String msg ) { System.out.println( "Sending via email: " + msg ); }}class StderrLogger extends Logger { public StderrLogger( int mask ) { this.mask = mask; } protected void writeMessage( String msg ) { System.out.println( "Sending to stderr: " + msg ); }}public class ChainOfResponsibilityExample{ public static void main( String[] args ) { // Build the chain of responsibility Logger l = new StdoutLogger( Logger.DEBUG).setNext( new EmailLogger( Logger.NOTICE ).setNext( new StderrLogger( Logger.ERR ) ) ); // Handled by StdoutLogger l.message( "Entering function y.", Logger.DEBUG ); // Handled by StdoutLogger and EmailLogger l.message( "Step1 completed.", Logger.NOTICE ); // Handled by all three loggers l.message( "An error has occurred.", Logger.ERR ); }}