Motivation: A problem has multiple well-defined solutions that conform to a common interface, and the client should be able to choose or switch between them at runtime.
Intent: Define a family of algorithms, encapsulate each one, and make them interchangeable behind a common interface.
What is it?
A strategy is an interchangeable part of a larger more complex system
You implement this pattern when you have a base object and multiple interchangeable parts you want to integrate into that base object.
The power
The gains are made when you are able to to mix and match these parts without re-implementing the base object
A good example of this is a camera with different lens attachments.
interface SortStrategy {
fun sort(data: MutableList<Int>)
}
class BubbleSort : SortStrategy {
override fun sort(data: MutableList<Int>) { /* ... */ }
}
class QuickSort : SortStrategy {
override fun sort(data: MutableList<Int>) { /* ... */ }
}
// Client code
class ReviewsViewer {
private val sortStrategy: SortStrategy = BubbleSort()
fun setSortStrategy(strategy: SortStrategy) {
sortStrategy = strategy
}
fun filterTopReviews(reviews: MutableList<Review>, count: Int = 5): List<Review> {
sortStrategy.sort(reviews.map{ it.rating })
return reviews.take(count)
}
}