責任鏈模式是一種設計模式。在責任鏈模式里,很多對象由每一個對象對其下家的引用而連線起來形成一條鏈。請求在這個鏈上傳遞,直到鏈上的某一個對象決定處理此請求。發出這個請求的客戶端並不知道鏈上的哪一個對象最終處理這個請求,這使得系統可以在不影響客戶端的情況下動態地重新組織和分配責任。
基本介紹
- 中文名:責任鏈模式
- 外文名:Chain of Responsibility
- 性質:一種設計模式
- 學科:計算機
簡介
角色
Java代碼示例
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 ); }}