Skip to content

Instantly share code, notes, and snippets.

@Sintrastes
Created March 6, 2022 20:38
Show Gist options
  • Save Sintrastes/1041f811a3775d6e628691b11c3c2a1c to your computer and use it in GitHub Desktop.
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.
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
}
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