Created
June 28, 2018 05:31
-
-
Save Hc747/cbc4e217abc2db3d4c7b43956c7c9534 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Entity | |
class Player(val name: String) : Entity | |
class NPC(val type: String) : Entity | |
enum class EventKey { | |
INIT, | |
PROCESS, | |
FINISH | |
} | |
typealias Event<T> = (T) -> Unit | |
class EntityModule<T : Entity>(private val entity: T) { | |
private val events = EnumMap<EventKey, MutableList<Event<T>>>(EventKey::class.java) | |
fun process(key: EventKey) { | |
val handlers = events[key] ?: return | |
handlers.forEach { it.invoke(entity) } | |
} | |
fun register(key: EventKey, event: Event<T>) { | |
val handlers = events[key] ?: mutableListOf() | |
handlers.add(event) | |
events[key] = handlers | |
} | |
fun deregister(key: EventKey, event: Event<T>) { | |
val handlers = events[key] ?: return | |
handlers.remove(event) | |
if (handlers.isEmpty()) { | |
events.remove(key) | |
} | |
} | |
} | |
object Main { | |
@JvmStatic | |
fun main(args: Array<String>) { | |
//player | |
val player = Player("Hc747") | |
//module | |
val module = EntityModule(player) | |
//events | |
val initialising: Event<Player> = { println("Initialising player with name: ${it.name}") } | |
val processing: Event<Player> = { println("Processing player with name: ${it.name}") } | |
val finishing: Event<Player> = { println("Finishing player with name: ${it.name}") } | |
with(module) { | |
register(EventKey.INIT, initialising) | |
register(EventKey.PROCESS, processing) | |
register(EventKey.FINISH, finishing) | |
register(EventKey.FINISH) { println("Some other event with the player when they finish, name: ${it.name}") } | |
} | |
module.process(EventKey.INIT) | |
module.process(EventKey.PROCESS) | |
module.process(EventKey.FINISH) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment