Skip to content

Instantly share code, notes, and snippets.

@kciesielski
Created November 22, 2012 20:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kciesielski/4132872 to your computer and use it in GitHub Desktop.
Save kciesielski/4132872 to your computer and use it in GitHub Desktop.
Functional decorator
object Rebates {
type RebatePolicy = (Product, Int, Money) => Money
}
object standardRebate extends ((Double, Int) => RebatePolicy) {
def apply(rebate: Double, minimalQuantity: Int) = {
(product, quantity, regularCost) => {
val rebateRatio = BigDecimal(rebate / 100)
if (quantity >= minimalQuantity)
regularCost * rebateRatio
else
Money(0)
}
}
}
object vipRebate extends
((Money, Money) => Option[RebatePolicy] => RebatePolicy) {
override def apply(minimalThreshold: Money, rebateValue: Money) =
(innerPolicy) => {
(product, quantity, regularCost) => {
val baseValue = innerPolicy.map(_(product, quantity, regularCost)).
getOrElse(regularCost)
if (baseValue > minimalThreshold)
(baseValue - rebateValue)
else baseValue
}
}
}
// somewhere in a rebate factory:
def createPolicy: RebatePolicy = {
val vipPolicy = vipRebate(Money(1000), Money(100))
val standard = standardRebate(10, 1)
if (isVip)
vipPolicy(Some(standard))
else
standard
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment