在Kotlin中,事件处理的设计模式有很多种,以下是一些常见的设计模式:
Observable
类和Observer
接口可以用来实现观察者模式。class EventPublisher {
private val observers = mutableListOf<Observer>()
fun addObserver(observer: Observer) {
observers.add(observer)
}
fun removeObserver(observer: Observer) {
observers.remove(observer)
}
fun notifyObservers(event: Event) {
observers.forEach { it.update(event) }
}
}
interface Observer {
fun update(event: Event)
}
interface Strategy {
fun execute(): String
}
class ConcreteStrategyA : Strategy {
override fun execute(): String {
return "Strategy A"
}
}
class ConcreteStrategyB : Strategy {
override fun execute(): String {
return "Strategy B"
}
}
class Context {
private var strategy: Strategy? = null
fun setStrategy(strategy: Strategy) {
this.strategy = strategy
}
fun executeStrategy(): String {
return strategy?.execute() ?: throw IllegalStateException("Strategy not set")
}
}
Function
接口和Runnable
接口来实现命令模式。interface Command {
fun execute()
}
class ConcreteCommandA(private val action: () -> Unit) : Command {
override fun execute() {
action()
}
}
class ConcreteCommandB(private val action: () -> Unit) : Command {
override fun execute() {
action()
}
}
class Receiver {
fun action() {
println("Action performed")
}
}
class Invoker {
private val commands = mutableListOf<Command>()
fun addCommand(command: Command) {
commands.add(command)
}
fun executeCommands() {
commands.forEach { it.execute() }
}
}
enum class
和sealed class
来实现状态模式。enum class State {
STATE_A,
STATE_B
}
class Context(private var state: State) {
fun setState(state: State) {
this.state = state
}
fun request() {
when (state) {
State.STATE_A -> handleStateA()
State.STATE_B -> handleStateB()
}
}
private fun handleStateA() {
println("Handling state A")
}
private fun handleStateB() {
println("Handling state B")
}
}
这些设计模式可以帮助你更好地组织和处理Kotlin中的事件。你可以根据具体需求选择合适的设计模式来实现事件处理。