vendredi 26 mars 2021

Plural class implementing singular. Is there a name for this design pattern?

Say I have a Product interface with a single method price():

interface Product {
  fun price(): Float
}

Now, I create a Products class that implements it:

class Products(private val products: List<Product>): Product {
  fun price() : Float {
    return products.fold(0f) { acc, fl -> acc + fl }
  }
}

Maybe Product is not the best example, but I find this pattern useful when you need to aggregate many products' price in many places of your codebase. This way, that logic is encapsulated in Products class.

I wonder if there is a name for this pattern.

Aucun commentaire:

Enregistrer un commentaire