1
2
3
4
5 class Trouble {
6 private int number;
7 public Trouble(int number) {
8 this.number = number;
9 }
10 public int getNumber() {
11 return number;
12 }
13 public String toString() {
14 return "[Trouble "+number+"]";
15 }
16 }
17
18 abstract class Support {
19 private String name;
20 private Support next;
21 public Support(String name) {
22 this.name = name;
23 }
24 public Support setNext(Support next) {
25 this.next = next;
26 return next;
27 }
28 public final void support(Trouble trouble) {
29 if(resolve(trouble)) {
30 done(trouble);
31 } else if(next != null) {
32 next.support(trouble);
33 } else {
34 fail(trouble);
35 }
36 }
37 public String toString() {
38 return "["+name+"]";
39 }
40 protected abstract boolean resolve(Trouble trouble);
41 protected void done(Trouble trouble) {
42 System.out.println(trouble+" is resolved by "+this+".");
43 }
44 protected void fail(Trouble trouble) {
45 System.out.println(trouble+" cannot be resolved.");
46 }
47 }
48
49 class NoSupport extends Support {
50 public NoSupport(String name) {
51 super(name);
52 }
53 protected boolean resolve(Trouble trouble) {
54 return false;
55 }
56 }
57
58 class LimitSupport extends Support {
59 private int limit;
60 public LimitSupport(String name, int limit) {
61 super(name);
62 this.limit = limit;
63 }
64 protected boolean resolve(Trouble trouble) {
65 if(trouble.getNumber() < limit) {
66 return true;
67 } else {
68 return false;
69 }
70 }
71 }
72
73 class OddSupport extends Support {
74 public OddSupport(String name) {
75 super(name);
76 }
77 protected boolean resolve(Trouble trouble) {
78 if(trouble.getNumber()%2 == 1) {
79 return true;
80 } else {
81 return false;
82 }
83 }
84 }
85
86 class SpecialSupport extends Support {
87 private int number;
88 public SpecialSupport(String name, int number) {
89 super(name);
90 this.number = number;
91 }
92 protected boolean resolve(Trouble trouble) {
93 if(trouble.getNumber() == number) {
94 return true;
95 } else {
96 return false;
97 }
98 }
99 }
100
101 public class ChainOfResponsibilityTrouble {
102 public static void main(String[] args) {
103 Support alice = new NoSupport("Alice");
104 Support bob = new LimitSupport("Bob", 100);
105 Support charlie = new SpecialSupport("Charlie", 429);
106 Support diana = new LimitSupport("Diana", 200);
107 Support elmo = new OddSupport("Elmo");
108 Support fred = new LimitSupport("Fred", 300);
109
110 alice.setNext(bob).setNext(charlie).setNext(diana).setNext(elmo).setNext(fred);
111 for(int i=0; i < 500; i+=33) {
112 alice.support(new Trouble(i));
113 }
114 }
115 }