Last active
March 2, 2019 14:51
-
-
Save anaelChardan/d8a43c0262cb24abfa01038b6f18b05b 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
import java.lang.reflect.ParameterizedType | |
interface Command | |
interface CommandHandler<C: Command> { | |
fun invoke(command: C) | |
} | |
class CommandBus(val handlers: List<CommandHandler<out Command>>) { | |
@PublishedApi | |
internal val commandToCommandHandler: Map<String, CommandHandler<out Command>> = | |
this.handlers.map { (it.javaClass.genericInterfaces[0] as ParameterizedType).actualTypeArguments[0].typeName to it }.toMap() | |
inline fun <reified C: Command> invoke(command: C) { | |
//TODO : Either if it does not exist | |
val handler = this.commandToCommandHandler.get(command::class.simpleName) | |
@Suppress("UNCHECKED_CAST") | |
(handler as CommandHandler<C>).invoke(command) | |
} | |
} | |
class SimpleCommand: Command | |
class SimpleCommandHandler: CommandHandler<SimpleCommand> { | |
override fun invoke(command: SimpleCommand) { | |
println("SIMPLE COMMAND") | |
} | |
} | |
class AnotherCommand: Command | |
class OtherCommandHandler: CommandHandler<AnotherCommand> { | |
override fun invoke(command: AnotherCommand) { | |
println("OTHER COMMAND") | |
} | |
} | |
fun main(vararg args: String) { | |
val simpleCommandHandler: SimpleCommandHandler = SimpleCommandHandler() | |
val otherCommandHandler: OtherCommandHandler = OtherCommandHandler() | |
val bus = CommandBus(listOf(simpleCommandHandler, otherCommandHandler)) | |
val command = SimpleCommand() | |
bus.invoke(command) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment