Android-ChainOfResponsibility责任链模式

责任链在Android中特别常用的设计模式,例如okhttp的intercepter等等.

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
//责任链模式
enum class Topic {
NONE, BUTTON, DIALOG, APPLICATION
}

private abstract class HelpHandler(var helpHandler: HelpHandler?, var topic: Topic) {
open fun handleHelp() {
helpHandler?.handleHelp()
}

open fun hasHelp(): Boolean {
return topic != Topic.NONE
}
}

private abstract class Widget(helpHandler: HelpHandler, topic: Topic) : HelpHandler(helpHandler, topic) {
init {
println(javaClass.name+" init()")
}
}

private class Button(helpHandler: HelpHandler, topic: Topic) : Widget(helpHandler, topic) {
override fun handleHelp() {
if (hasHelp()) {
println(javaClass.name + " " + Thread.currentThread().stackTrace[1].methodName)
} else {
super.handleHelp()
}
}
}

private class Dialog(helpHandler: HelpHandler, topic: Topic) : Widget(helpHandler, topic) {
override fun handleHelp() {
if (hasHelp()) {
println(javaClass.name + " " + Thread.currentThread().stackTrace[1].methodName)
} else {
super.handleHelp()
}
}
}

private class Application(helpHandler: HelpHandler?, topic: Topic) : HelpHandler(helpHandler, topic) {
constructor(topic: Topic) : this(null, topic) {
}
}

fun main(){
var application = Application(Topic.APPLICATION)
var dialog = Dialog(application, Topic.DIALOG)
var button = Button(dialog, Topic.BUTTON)
button.handleHelp()

var button1 = Button(dialog, Topic.NONE)
button1.handleHelp()
}

Android-ChainOfResponsibility责任链模式
http://example.com/2021/12/07/Android-ChainOfResponsibility责任链模式/
作者
xdd
发布于
2021年12月7日
许可协议