Created
November 22, 2012 20:49
-
-
Save kciesielski/4132872 to your computer and use it in GitHub Desktop.
Functional decorator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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