-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChainOfResponsibility.kt
72 lines (63 loc) · 1.91 KB
/
ChainOfResponsibility.kt
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
package chainofresposibility
/**
* @author ranaaditya
*
* Chain of Responsibility Design Pattern
*
* Chain of responsibility pattern is used to achieve loose coupling
* in software design where a request from the client is passed to a
* chain of objects to process them. Later, the object in the chain
* will decide themselves who will be processing the request and whether
* the request is required to be sent to the next object in the chain or not.
*/
class Chain {
var chain: Processor? = null
private fun buildChain() {
chain = NegativeProcessor(ZeroProcessor(PositiveProcessor(null)))
}
fun process(request: processNumber?) {
chain!!.process(request)
}
init {
buildChain()
}
}
abstract class Processor(private val processor: Processor?) {
open fun process(request: processNumber?) {
processor?.process(request)
}
}
class processNumber(val number: Int)
class NegativeProcessor(processor: Processor) : Processor(processor) {
override fun process(request: processNumber?) {
if (request!!.number < 0) {
println("NegativeProcessor : " + request.number)
} else {
super.process(request)
}
}
}
class ZeroProcessor(processor: Processor) : Processor(processor) {
override fun process(request: processNumber?) {
if (request!!.number == 0) {
println("ZeroProcessor : " + request.number)
} else {
super.process(request)
}
}
}
class PositiveProcessor(processor: Processor?) : Processor(processor) {
override fun process(request: processNumber?) {
if (request!!.number > 0) {
println("PositiveProcessor : " + request.number)
} else {
super.process(request)
}
}
}
fun main() {
val chain = Chain()
chain.process(processNumber(9))
chain.process(processNumber(1))
chain.process(processNumber(1))
}