Created
March 6, 2022 20:38
-
-
Save Sintrastes/1041f811a3775d6e628691b11c3c2a1c to your computer and use it in GitHub Desktop.
Example showing how to decouple interface from implementation in an example from Robert Martin using generics.
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
package com.myorg.myapp.api | |
data class AlbumData( | |
val title: String, | |
val released: DateTime, | |
val artist: String | |
) | |
interface AlbumService { | |
suspend fun getAlbums(): List<AlbumData> | |
} | |
interface Application<E>: MakeAlbumService<E> { | |
fun runApplication() | |
} | |
interface MakeAlbumService<E> { | |
fun makeService(label: E): AlbumService | |
} |
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
package com.myorg.myapp.implementation | |
import com.myorg.myapp.api.* | |
enum class ServiceType { | |
Local, Remote; | |
} | |
object AlbumApplication: Application<ServiceType> { | |
override fun makeService(label: ServiceType): AlbumService = | |
when (label) { | |
ServiceType.Local -> LocalAlbumService() | |
ServiceType.Remote -> RemoteAlbumService() | |
} | |
override fun runApplication() { | |
... | |
} | |
} | |
class LocalAlbumService: AlbumService { | |
... | |
} | |
class RemoteAlbumService: AlbumService { | |
... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment