Skip to content

Instantly share code, notes, and snippets.

@dodalovic
Last active May 30, 2017 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dodalovic/4ee9939ab645b9d9933da1b4f14edf7d to your computer and use it in GitHub Desktop.
Save dodalovic/4ee9939ab645b9d9933da1b4f14edf7d to your computer and use it in GitHub Desktop.
Strategy pattern implementation in kotlin

Strategy pattern implementation in kotlin (kotlinlang.org) language

Important
make sure to have kotlinc on your $PATH

Running

  • Without any command line arguments

    $ kotlinc -script strategy.kts 200
    java.lang.IllegalArgumentException: Invalid speed
            at Strategy.<init>(strategy.kts:9)
  • Slow pace town building

    kotlinc -script strategy.kts slow
    
    Building at slow pace...
    
    Town built in 3000 milliseconds!
  • Medium pace town building

    kotlinc -script strategy.kts medium
    
    Building at medium pace...
    
    Town built in 1500 milliseconds!
  • Fast pace town building

    kotlinc -script strategy.kts fast
    
    Building at fast pace...
    
    Town built in 50 milliseconds!
class TownBuilder(val buildingStrategy: () -> Long) {
fun build() {
val pace = buildingStrategy.invoke()
Thread.sleep(pace)
println("Town built in $pace milliseconds!")
}
}
TownBuilder(
when(args[0]) {
"slow" -> {
println("\nBuilding at slow pace...\n")
fun() = 3000L
}
"medium" -> {
println("\nBuilding at medium pace...\n")
fun() = 1500L
}
"fast" -> {
println("\nBuilding at fast pace...\n")
fun() = 50L
}
else -> throw IllegalArgumentException("Invalid speed")
}
).build()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment