责任链模式

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

/**
* @Author Liruilong
* @Description 责任链模式
* 创建处理对象序列的一种通用方案,
* 一个对象可能需要在完成一些工作之后,将结果传递到另一个对象,
* @Date 9:57 2019/9/5
* @Param
* @return
**/
class Processing{
// 创建两个处理对象
static class HeaderTextProcessing extends ProcessingObject<String>{

@Override
protected String handleWork(String input) {
return "Form Raoul , Mario and Alan:" + input;
}
}
static class SpellCheckerProcessing extends ProcessingObject<String>{

@Override
protected String handleWork(String input) {
// 字符串的替换
return input.replaceAll("labda", "lambda");
}
}



public static void main(String[] args) {
// 使用责任链模式
ProcessingObject<String> p1 = new HeaderTextProcessing();
ProcessingObject<String> p2 = new SpellCheckerProcessing();
// 由p2对象构造p1对象.
p1.setSuccesstor(p2);
//
String result = p1.handle("Arent t labdas really sexy ?!!");
System.out.println(result);

}
}
abstract class ProcessingObject<T>{
protected ProcessingObject<T> successtor;

public void setSuccesstor(ProcessingObject<T> successtor) {
this.successtor = successtor;
}

// 对传入的对象进行处理
public T handle(T input){
T r = handleWork(input);
if (successtor != null){
return successtor.handle(input);
}
return r;
}
abstract protected T handleWork(T input);
}