14) chain of responsibility pattern
类别:
behavioral pattern
问题:
高耦合,不灵活
if(){ }else if(){ }else if(){ } ...
方案:
示例:
public class ChainOfResponsibilityPattern { public static void main(String[] args) { // 灵活装配 Pipeline node1 = new Node1(1); Pipeline node2 = new Node2(2); Pipeline node3 = new Node3(3); node1.setNextNode(node2); node2.setNextNode(node3); // 固定用法 node1.load(new Message(2, "need be handled by node2")); node1.load(new Message(1, "need be handled by node1")); node1.load(new Message(3, "need be handled by node3")); } } abstract class Pipeline { protected int level; // next element in chain or responsibility protected Pipeline nextNode; public void setNextNode(Pipeline nextNode) { if (nextNode == null) { throw new IllegalArgumentException(""); } this.nextNode = nextNode; } public void load(Message msg) { if (msg == null) { throw new IllegalArgumentException("message not be null"); } if (this.level == msg.getLevel()) { process(msg.getMsg()); } else if (this.nextNode != null) { nextNode.load(msg); } else { // the last node can not handle the message throw new IllegalStateException("can not handle the message"); } } abstract protected void process(String message); } class Node1 extends Pipeline { public Node1(int level) { this.level = level; } @Override protected void process(String message) { System.out.println("done by node1: " + message); } } class Node2 extends Pipeline { public Node2(int level) { this.level = level; } @Override protected void process(String message) { System.out.println("done by node2: " + message); } } class Node3 extends Pipeline { public Node3(int level) { this.level = level; } @Override protected void process(String message) { System.out.println("done by node3: " + message); } } class Message { private int level; private String msg; public Message(int level, String msg) { this.level = level; this.msg = msg; } public int getLevel() { return level; } public String getMsg() { return msg; } }
done by node2: need be handled by node2 done by node1: need be handled by node1 done by node3: need be handled by node3
应用:
不足:(
优化:)