Created
November 22, 2021 01:40
-
-
Save darylsze/2f6486ae4b6f8692d09ce072fc986f82 to your computer and use it in GitHub Desktop.
Contract calculation by using visitor pattern
This file contains 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
interface IReportVisitable { | |
fun accept(visitor: IReportVisitor): Int | |
} | |
data class FixedPriceContract( | |
val costPerYear: Int | |
) : IReportVisitable { | |
override fun accept(visitor: IReportVisitor): Int { | |
return visitor.visit(this) | |
} | |
} | |
data class TimeAndMaterialsContract( | |
val costPerHour: Int, | |
val totalHours: Int | |
) : IReportVisitable { | |
override fun accept(visitor: IReportVisitor): Int { | |
return visitor.visit(this) | |
} | |
} | |
data class SupportContract( | |
val costPerMonth: Int | |
) : IReportVisitable { | |
override fun accept(visitor: IReportVisitor): Int { | |
return 0 | |
} | |
} | |
interface IReportVisitor { | |
fun visit(contract: FixedPriceContract): Int | |
fun visit(contract: TimeAndMaterialsContract): Int | |
fun visit(contract: SupportContract): Int | |
} | |
class YearCostReportVisitor: IReportVisitor { | |
override fun visit(contract: FixedPriceContract): Int { | |
return contract.costPerYear | |
} | |
override fun visit(contract: TimeAndMaterialsContract): Int { | |
return contract.totalHours * contract.costPerHour | |
} | |
override fun visit(contract: SupportContract): Int { | |
return contract.costPerMonth * 12 | |
} | |
} | |
val projectAlpha = FixedPriceContract(costPerYear = 10000) | |
val projectGamma = TimeAndMaterialsContract(totalHours = 150, costPerHour = 10) | |
val projectBeta = SupportContract(costPerMonth = 500) | |
val projectKappa = TimeAndMaterialsContract(totalHours = 50, costPerHour = 50) | |
val visitor = YearCostReportVisitor() | |
val projects = arrayOf(projectAlpha, projectBeta, projectGamma, projectKappa) | |
val cost = projects.map { it.accept(visitor) }.sum() | |
print(cost) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment