Created
January 26, 2022 23:12
-
-
Save renatojobal/2df26dd39f3fb06f6705ed2c8447b4dc to your computer and use it in GitHub Desktop.
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
data class Student( | |
val name : String, | |
val email : String, | |
val age : Int | |
) | |
interface StrategyCustom { | |
abstract fun doAlgorithm(data: MutableList<Student>) : MutableList<Student> | |
} | |
class Context(private var strategy: StrategyCustom) { | |
fun setStrategyCustom(newStrategy: StrategyCustom){ | |
this.strategy = newStrategy | |
} | |
fun doSomeBusinessLogic(data: MutableList<Student>) { | |
println("Sorting elements with strategy: ${strategy.javaClass.name}") | |
val result = this.strategy.doAlgorithm(data = data) | |
println("Result $result") | |
} | |
} | |
class StrategyName : StrategyCustom { | |
override fun doAlgorithm(data: MutableList<Student>): MutableList<Student> { | |
data.sortBy { student -> | |
student.name | |
} | |
return data | |
} | |
} | |
class StrategyAge : StrategyCustom { | |
override fun doAlgorithm(data: MutableList<Student>): MutableList<Student> { | |
data.sortBy { student -> | |
student.age | |
} | |
return data | |
} | |
} | |
fun main() { | |
val exampleList = mutableListOf<Student>( | |
Student( | |
name = "Ximena Puchaicela", | |
email = "ff.edu.ec", | |
age = 20 | |
), | |
Student( | |
name = "Maria Fernanda Ordoñez", | |
email = "[email protected]", | |
age = 24 | |
), | |
Student( | |
name = "Juan José Yanangomez", | |
email = "[email protected]", | |
age = 25 | |
), | |
Student( | |
name = "EE", | |
email = "e.edu.ec", | |
age = 27 | |
) | |
) | |
// Create context object with strategy A | |
val context = Context(strategy = StrategyName()) | |
// Sort objects with A strategy | |
context.doSomeBusinessLogic(exampleList) | |
// Change strategy to B | |
context.setStrategyCustom(newStrategy = StrategyAge()) | |
// Sort again object with B strategy | |
context.doSomeBusinessLogic(exampleList) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What Language? @renatojobal