文章目录
  1. 责任链模式

责任链模式

  • 使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一个链,沿着链条传递请求,知道有一个对象处理为止。

ChainOfResponsibility

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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
public interface PhoneMakerAssembly {
void setNextPoint(PhoneMakerAssembly successor);
PhoneMakerAssembly getNextPoint();
void build(String partName);
}
public abstract class AbstractPhoneMakerAssembly implements PhoneMakerAssembly {
private PhoneMakerAssembly nextpoint;
@Override public void setNextPoint(PhoneMakerAssembly successor) {
nextpoint=successor;
}
@Override public PhoneMakerAssembly getNextPoint() {
return nextpoint;
}
}
public class Framemaker extends AbstractPhoneMakerAssembly{
@Override public void build(String partName) {
if ("main".equals(partName)){
System.out.println("构建主体框架");
return;
}
System.out.println("构建失败,寻找下家");
getNextPoint().build(partName);
}
}
public class CameraMaker extends AbstractPhoneMakerAssembly{
@Override public void build(String partName) {
if ("camera".equals(partName)){
System.out.println("构建摄像头框架");
return;
}
System.out.println("构建失败,寻找下家");
getNextPoint().build(partName);
}
}
public class ScreenMaker extends AbstractPhoneMakerAssembly{
@Override public void build(String partName) {
if ("screen".equals(partName)){
System.out.println("构建屏幕框架");
return;
}
System.out.println("构建失败,寻找下家");
getNextPoint().build(partName);
}
}
public class DefaultMaker implements PhoneMakerAssembly {
@Override public void setNextPoint(PhoneMakerAssembly successor) {
}
@Override public PhoneMakerAssembly getNextPoint() {
return null;
}
@Override public void build(String partName) {
System.out.println("未找到支持的构建器");
}
}
public class App {
public static void main(String[] args) {
PhoneMakerAssembly maker1=new Framemaker();
PhoneMakerAssembly maker2=new CameraMaker();
PhoneMakerAssembly maker3=new ScreenMaker();
maker1.setNextPoint(maker2);
maker2.setNextPoint(maker3);
maker3.setNextPoint(new DefaultMaker());
//注意链条是代码构造出来的
maker1.build("screen");
maker1.build("main");
maker1.build("camera");
maker1.build("xxx");
}
}
文章目录
  1. 责任链模式