Skip to content

Instantly share code, notes, and snippets.

@darylsze
Last active November 21, 2021 08:13
Show Gist options
  • Save darylsze/89d857fbc3a497e2c50345ea36989a01 to your computer and use it in GitHub Desktop.
Save darylsze/89d857fbc3a497e2c50345ea36989a01 to your computer and use it in GitHub Desktop.
Contract calculator in Visitor pattern but simplied
interface IContracts
interface ICalculator {
fun calculate(vararg contracts: IContracts): Int
}
data class FixedPriceContract(
val costPerYear: Int
) : IContracts
data class TimeAndMaterialsContract(
val costPerHour: Int,
val totalHours: Int
) : IContracts
data class SupportContract(
val costPerMonth: Int
) : IContracts
object YearCostReportCalculator : ICalculator {
override fun calculate(
vararg contracts: IContracts
): Int {
return contracts.map {
when (it) {
is FixedPriceContract -> it.costPerYear
is TimeAndMaterialsContract -> it.costPerHour * it.totalHours
is SupportContract -> it.costPerMonth * 12
else -> throw NotImplementedError()
}
}.sum()
}
}
object MonthCostReportCalculator : ICalculator {
override fun calculate(
vararg contracts: IContracts
): Int {
return contracts.map {
when (it) {
is FixedPriceContract -> it.costPerYear / 12
is TimeAndMaterialsContract -> it.costPerHour * it.totalHours
is SupportContract -> it.costPerMonth
else -> throw NotImplementedError()
}
}.sum()
}
}
object SupportCostReportCalculator : ICalculator {
override fun calculate(vararg contracts: IContracts): Int {
return contracts.map {
when (it) {
is FixedPriceContract -> it.costPerYear / 12
is TimeAndMaterialsContract -> it.costPerHour * it.totalHours
is SupportContract -> it.costPerMonth
else -> throw NotImplementedError()
}
}.sum()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment