Skip to content

Instantly share code, notes, and snippets.

@renatojobal
Created January 26, 2022 23:12
Show Gist options
  • Save renatojobal/2df26dd39f3fb06f6705ed2c8447b4dc to your computer and use it in GitHub Desktop.
Save renatojobal/2df26dd39f3fb06f6705ed2c8447b4dc to your computer and use it in GitHub Desktop.
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)
}
@MrVanQish
Copy link

MrVanQish commented Nov 12, 2022

What Language? @renatojobal

@renatojobal
Copy link
Author

@MrVanQish kotlin

@MrVanQish
Copy link

Ty

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment