-
Notifications
You must be signed in to change notification settings - Fork 1
/
chainOfResponsibility.java
66 lines (57 loc) · 1.53 KB
/
chainOfResponsibility.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
interface Handler {
void setNextHandler(Handler nextHandler);
void handle(int req);
}
class Handler1 implements Handler {
Handler nextHandler;
@Override
public void setNextHandler(Handler nextHandler) {
this.nextHandler = nextHandler;
}
@Override
public void handle(int req) {
if(req >= 0 && req < 10)
System.out.println("I am the first handler");
else
nextHandler.handle(req);
}
}
class Handler2 implements Handler {
Handler nextHandler;
@Override
public void setNextHandler(Handler nextHandler) {
this.nextHandler = nextHandler;
}
@Override
public void handle(int req) {
if(req >= 10 && req < 20)
System.out.println("I am second handler");
else
nextHandler.handle(req);
}
}
class Handler3 implements Handler {
@Override
public void setNextHandler(Handler nextHandler) {
}
@Override
public void handle(int req) {
if(req >= 20)
System.out.println("I am third handler");
else
System.out.println("The req cannot be solved");
}
}
public class Main {
public static void main(String[] args){
Handler handler1 = new Handler1();
Handler handler2 = new Handler2();
Handler handler3 = new Handler3();
handler1.setNextHandler(handler2);
handler2.setNextHandler(handler3);
int[] req_arr = {25, 35, 1, 5, 15};
for(int req : req_arr){
handler1.handle(req);
}
}
}