在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中的事件。你可以根據具體需求選擇合適的設計模式來實現事件處理。