【问题标题】:Plural class implementing singular. Is there a name for this design pattern?复数类实现单数。这种设计模式有名字吗?
【发布时间】:2021-03-26 09:14:56
【问题描述】:

假设我有一个Product 接口和单个方法price()

interface Product {
  fun price(): Float
}

现在,我创建一个实现它的Products 类:

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

也许Product 不是最好的例子,但是当您需要在代码库的许多地方汇总许多产品的价格时,我发现这种模式很有用。这样,该逻辑就被封装在Products 类中。

我想知道这种模式是否有名字。

【问题讨论】:

  • 我只是好奇:那是哪种编程语言?
  • 这是 Kotlin。感谢您的回答!

标签: oop design-patterns


【解决方案1】:

如果我正确理解了代码,这看起来像是Composite design pattern 的示例。


看起来您已经使用折叠实现了复合逻辑,这与Composite design pattern is isomorphic to monoidsmonoids accumulate 的观察结果一致。您在那里使用的特定幺半群是加法幺半群。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 2011-04-23
    • 2021-06-18
    • 1970-01-01
    相关资源
    最近更新 更多