Manual Delegation
This works. However, arguably, it breaks encapsulation. The consumer of ItemViewModel
perhaps should not have direct access to the FavoriteStore
. Instead, ItemViewModel
should have an API for working with favorites that hides the fact that there even is a FavoriteStore
.
So, we could set up manual delegation, where ItemViewModel
forwards the FavoriteStore
API on to favorites
:
class ItemViewModel(private val favorites: FavoriteStore<Item>) : FavoriteStore<Item> {
override fun isFavorite(thingy: Item) = favorites.isFavorite(thingy)
override fun toggleFavorite(thingy: Item, isFavorite: Boolean) = favorites.toggleFavorite(thingy, isFavorite)
}
fun main() {
val vm = ItemViewModel(InMemoryFavoriteStore())
val item = Item("this is my id", "this is my name")
println("item isFavorite: ${vm.isFavorite(item)}")
vm.toggleFavorite(item, true)
println("item isFavorite: ${vm.isFavorite(item)}")
}
This also works, and for a small interface like FavoriteStore
, it is not too tedious to implement. The bigger the API surface, though, the more work is involved in setting up this manual delegation.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.