Created
April 17, 2020 22:37
-
-
Save 422404/c0aa1986ec9e69e1005b506f660911f3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* Nice annotation instead of putting a comment | |
* Only for readability purpose | |
*/ | |
@Target(AnnotationTarget.PROPERTY) | |
@Retention(AnnotationRetention.SOURCE) | |
private annotation class Provides | |
/** | |
* Nice annotation instead of putting a comment | |
* Only for readability purpose | |
*/ | |
@Target(AnnotationTarget.PROPERTY) | |
@Retention(AnnotationRetention.SOURCE) | |
private annotation class Requires | |
/** | |
* Takes a function to construct a part of a composite component | |
*/ | |
private fun <T: Any> part(builder: () -> T) = lazy(builder) | |
/** | |
* Takes a function to construct a part of a composite component | |
* and a function to be executed with the constructed component | |
* as receiver to proceed to services binding | |
*/ | |
private fun <T: Any> part(builder: () -> T, binder: T.() -> Unit) = | |
lazy { | |
val instance = builder() | |
instance.binder() | |
instance | |
} | |
/** | |
* Some client component type | |
*/ | |
private interface ClientType { | |
var service: () -> Unit | |
} | |
/** | |
* Some client component implementation | |
*/ | |
private class ClientImpl: ClientType { | |
@Requires | |
override lateinit var service: () -> Unit | |
} | |
/** | |
* Some server component type | |
*/ | |
private interface ServerType { | |
val serverService: () -> Unit | |
} | |
/** | |
* Some server component implementation | |
*/ | |
private class ServerImpl: ServerType { | |
@Provides | |
override val serverService = { println("Helloworld!") } | |
} | |
/** | |
* Some composite component type | |
*/ | |
private abstract class CompositeType { | |
private val client: ClientType by part(::createClient) { | |
service = server.serverService | |
} | |
private val server: ServerType by part(::createServer) | |
@Provides | |
val service = client.service | |
abstract fun createClient(): ClientType | |
abstract fun createServer(): ServerType | |
} | |
/** | |
* Some composite component implementation | |
*/ | |
private class CompositeImpl: CompositeType() { | |
override fun createClient() = ClientImpl() | |
override fun createServer() = ServerImpl() | |
} | |
fun main() { | |
val component = CompositeImpl() | |
component.service() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment