Kotlin strategy pattern

How to write a strategy pattern in Kotlin

An example of a strategy pattern in Kotlin.

Table of contents for design patterns in Kotlin

In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use. Wikipedia

Example:

BillStrategy

interface BillStrategy {
    fun calculatePrice(orderPrice: Double): Double
}

class StandardCustomerBillStrategy : BillStrategy {
    override fun calculatePrice(orderPrice: Double) = orderPrice
}

open class DiscountBillStrategy(private val discount: Int) : BillStrategy {
    override fun calculatePrice(orderPrice: Double): Double = orderPrice - (orderPrice * discount / 100)
}

class NewCustomerBillStrategy : DiscountBillStrategy(20)

class RegularCustomerBillStrategy : DiscountBillStrategy(10)

Order

class Order(private val billStrategy: BillStrategy) {

    private val items = mutableListOf<Double>()

    fun addItem(price: Double) = items.add(price)

    fun calcPrice(): Double = billStrategy.calculatePrice(items.sumByDouble { it })
}

Usage:

fun main() {
    Order(NewCustomerBillStrategy()).apply {
        addItem(40.0)
        addItem(60.0)
        println(calcPrice())
    }

    Order(StandardCustomerBillStrategy()).apply {
        addItem(40.0)
        addItem(60.0)
        println(calcPrice())
    }

    Order(RegularCustomerBillStrategy()).apply {
        addItem(40.0)
        addItem(60.0)
        println(calcPrice())
    }
}

Result

80.0
100.0
90.0