Strategy Pattern

In Strategy pattern, a class behavior or its algorithm can be changed at run time. This type of design pattern comes under behavior pattern.

In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object. The strategy object changes the executing algorithm of the context object.


class Printer(val strategy: (String) -> String) {
    fun print(string: String): String = strategy(string)
}
val lowerCaseFormatter: (String) -> String = String::toLowerCase
val upperCaseFormatter: (String) -> String = String::toUpperCase
fun main(args: Array<String>) {
    val lower = Printer(strategy = lowerCaseFormatter)
    println(lower.print("O tempora, o mores!"))
    val upper = Printer(strategy = upperCaseFormatter)
    println(upper.print("O tempora, o mores!"))
}			

Output of kotlin strategy pattern


o tempora, o mores!
O TEMPORA, O MORES!	


Another Example for kotlin Strategy Design Pattern


interface BookingStrategy {
    val fare: Double
}

class CarBookingStrategy : BookingStrategy {

    override val fare: Double = 12.5

    override fun toString(): String {
        return "CarBookingStrategy"
    }
}

class TrainBookingStrategy : BookingStrategy {

    override val fare: Double = 8.5

    override fun toString(): String {
        return "TrainBookingStrategy"
    }
}

class Customer(var bookingStrategy: BookingStrategy) {

    fun calculateFare(numOfPassangeres: Int): Double {
        val fare = numOfPassangeres * bookingStrategy.fare
        println("Calculating fares using " + bookingStrategy)
        return fare
    }
}

fun main(args: Array<String>) {

    //CarBooking Strategy
    val cust = Customer(CarBookingStrategy())
    var fare = cust.calculateFare(5)
    println(fare)

    //TrainBooking Strategy
    cust.bookingStrategy = TrainBookingStrategy()
    fare = cust.calculateFare(5)
    println(fare)
}			

Output of kotlin strategy pattern


Calculating fares using CarBookingStrategy
62.5
Calculating fares using TrainBookingStrategy
42.5

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions