責任鏈模式, Chain of Responsibility, Java實現 ...
責任鏈模式-Chain of Responsibility
在這種模式中,通常每個接收者都包含對另一個接收者的引用。如果一個對象不能處理該請求,那麼它會把相同的請求傳給下一個接收者,依此類推。
咱們在這裡換一個場景:
國王(King類), 經常會遇到各種麻煩(Trouble類), 而國王一旦遇到麻煩, 則會把麻煩交給手下去做.
國王有一天上了戰場, 任務法派的順序是這樣的, 騎兵先上, 騎兵不行步兵上, 步兵不行就換貼身侍衛上.
TroubleType枚舉
在這裡枚舉了, 國王在戰場上有三種事情會分派給手下去做
public enum TroubleType { DEFEND, ATTACK, PROTECT }
Trouble類
這裡是國王分配的事情
public class Trouble { private final TroubleType troubleType; private final String requestDescription; public Trouble(final TroubleType troubleType, final String requestDescription) { this.troubleType = Objects.requireNonNull(troubleType); this.requestDescription = Objects.requireNonNull(requestDescription); } public String getRequestDescription() { return requestDescription; } public TroubleType getRequestType() { return troubleType; } @Override public String toString() { return getRequestDescription(); } }
Support抽象類
國王的手下解決Trouble都會實現這個Support藉口, Support藉口是解決Trouble的統一定義
public abstract class Support { private Support next; public Support(Support next) { this.next = next; } public void handleRequest(Trouble trouble) { if (next != null) { next.handleRequest(trouble); } } protected void printHandling(Trouble trouble) { System.out.printf("%s 執行任務: %s\n", this, trouble); } @Override public abstract String toString(); }
RiderSupport類
騎兵在本例子中只負責進攻
public class RiderSupport extends Support { public RiderSupport(Support support) { super(support); } @Override public void handleRequest(Trouble trouble) { if (trouble.getRequestType().equals(TroubleType.ATTACK)) { printHandling(trouble); } else { super.handleRequest(trouble); } } @Override public String toString() { return "Rider"; } }
SolderSupport類
步兵在本例子中只負責防守
public class SolderSupport extends Support { public SolderSupport(Support support) { super(support); } @Override public void handleRequest(Trouble trouble) { if (trouble.getRequestType().equals(TroubleType.DEFEND)) { printHandling(trouble); } else { super.handleRequest(trouble); } } @Override public String toString() { return "Soldier"; } }
GuardSupport類
本類負責保衛國王
public class GuardSupport extends Support { public GuardSupport(Support next) { super(next); } @Override public void handleRequest(Trouble trouble) { if (trouble.getRequestType().equals(TroubleType.PROTECT)) { printHandling(trouble); } else { super.handleRequest(trouble); } } @Override public String toString() { return "Guard"; } }
King類
本類負責維護責任鏈.
public class King { private Support chain; public King() { buildChain(); } private void buildChain() { chain = new RiderSupport(new SolderSupport(new GuardSupport(null))); } public void resolve(Trouble trouble) { chain.handleRequest(trouble); } }
Main
運行測試
public class Main { public static void main(String[] args) { King king = new King(); king.resolve(new Trouble(TroubleType.DEFEND, "防禦")); king.resolve(new Trouble(TroubleType.ATTACK, "進攻")); king.resolve(new Trouble(TroubleType.PROTECT, "保護國王")); } }