在這種模式中,一般每一個接收者都包含對另外一個接收者的引用。若是一個對象不能處理該請求,那麼它會把相同的請求傳給下一個接收者,依此類推。java
本類是:待責任鏈來處理的問題Trouble類.ide
本例子較簡單, Trouble只有一個int型做爲待處理的編號.測試
public class Trouble { private int number; public Trouble(int number) { this.number = number; } public int getNumber() { return number; } public String toString() { return "[Trouble " + number + "]"; } }
Support類是責任鏈中的節點抽象出來的統必定義.this
public abstract class Support { private String name; private Support next; public Support(String name) { this.name = name; } public Support setNext(Support next) { this.next = next; return next; } protected abstract boolean solve(Trouble trouble); protected void done(Trouble trouble) { // 解決 System.out.println(trouble + " is resolved by " + this + "."); } protected void fail(Trouble trouble) { // 未解決 System.out.println(trouble + " cannot be resolved."); } public void execute(Trouble trouble) { if (solve(trouble)) { done(trouble); } else if (next != null) { next.execute(trouble); } else { fail(trouble); } } public String toString() { return "[" + name + "]"; } }
本類專門用於處理trouble編號爲0的對象
/** * 本類專門用於處理trouble爲0的狀況 */ public class ZeroSupport extends Support { public ZeroSupport(String name) { super(name); } @Override protected boolean solve(Trouble trouble) { if (trouble.getNumber() == 0) { return true; } else { return false; } } }
只要Trouble的編號小於本類的成員變量limit的值, 那麼LimitSupport類的實例就能夠處理這個Troubleblog
/** * 本類專門用於處理trouble值小於limit的狀況 */ public class LimitSupport extends Support { private int limit; public LimitSupport(String name, int limit) { super(name); this.limit = limit; } @Override protected boolean solve(Trouble trouble) { if (trouble.getNumber() < limit) { return true; } else { return false; } } }
只要Trouble的編號是奇數, 那麼OddSupport類的實例就能夠處理這個Trouble.get
/** * 本類專門用於處理trouble爲奇數的狀況 */ public class OddSupport extends Support { public OddSupport(String name) { super(name); } @Override protected boolean solve(Trouble trouble) { if (trouble.getNumber() % 2 == 1) { return true; } else { return false; } } }
用於測試運行it
public class Main { public static void main(String[] args) { Support charlie = new ZeroSupport("Charlie"); Support bob = new LimitSupport("Bob", 100); Support diana = new LimitSupport("Diana", 200); Support elmo = new OddSupport("Elmo"); Support fred = new LimitSupport("Fred", 300); // 造成職責鏈 charlie.setNext(bob).setNext(diana).setNext(elmo).setNext(fred); // 製造各類問題, 並讓這個責任鏈來處理 for (int i = 0; i < 500; i += 33) { charlie.execute(new Trouble(i)); } } }