main.io.github.chengzis.chain.InterceptorList.kt Maven / Gradle / Ivy
package io.github.chengzis.chain
/**
* 拦截器集合
*/
class InterceptorList : List> {
private val nodes = mutableListOf>()
/**
* 拦截器的节点
*/
private inner class Node(val priority: Int, val interceptor: Interceptor) :
Comparable> {
override fun compareTo(other: Node): Int {
return priority.compareTo(other.priority)
}
}
fun add(priority: Int, interceptor: Interceptor) {
nodes.add(Node(priority, interceptor))
nodes.sortDescending()
}
fun add(priority: Int, block: (Chain, T) -> R) = add(priority, LambdaInterceptor(block))
override val size: Int
get() = nodes.size
override fun contains(element: Interceptor): Boolean {
return nodes.any { it.interceptor == element }
}
override fun containsAll(elements: Collection>): Boolean {
return nodes.map { it.interceptor }.containsAll(elements)
}
override fun get(index: Int): Interceptor {
return nodes[index].interceptor
}
override fun indexOf(element: Interceptor): Int {
return nodes.indexOfFirst { it.interceptor == element }
}
override fun isEmpty(): Boolean {
return nodes.isEmpty()
}
override fun iterator(): Iterator> {
return nodes.map { it.interceptor }.iterator()
}
override fun lastIndexOf(element: Interceptor): Int {
return nodes.indexOfLast { it.interceptor == element }
}
override fun listIterator(): ListIterator> {
return nodes.map { it.interceptor }.listIterator()
}
override fun listIterator(index: Int): ListIterator> {
return nodes.map { it.interceptor }.listIterator(index)
}
override fun subList(fromIndex: Int, toIndex: Int): List> {
return nodes.subList(fromIndex, toIndex).map { it.interceptor }
}
private class LambdaInterceptor(private val block: (Chain, T) -> R) :
Interceptor {
override fun process(chain: Chain, args: T): R {
return block.invoke(chain, args)
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy