-
Notifications
You must be signed in to change notification settings - Fork 109
/
Strategy.kt
84 lines (71 loc) · 2.14 KB
/
Strategy.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package design_patterns
/**
*
* Strategy is a behavioral design pattern used to define a family of algorithms,
*
* encapsulate each one and make them interchangeable
*
*/
// encapsulates the filtering algorithm
interface FoodFilterStrategy {
fun filter(items: List<FoodEntity>): List<FoodEntity>
}
class OnlyChipsFilterStrategy : FoodFilterStrategy {
override fun filter(items: List<FoodEntity>): List<FoodEntity> {
return items.filter { it.category == "chips" }
}
}
class OnlyChocolateFilterStrategy : FoodFilterStrategy {
override fun filter(items: List<FoodEntity>): List<FoodEntity> {
return items.filter { it.category == "chocolate" }
}
}
class PriceFilterStrategy(private val price: Int) : FoodFilterStrategy {
override fun filter(items: List<FoodEntity>): List<FoodEntity> {
return items.filter { it.price >= price }
}
}
class SearchWordFilterStrategy(private val search: String) : FoodFilterStrategy {
override fun filter(items: List<FoodEntity>): List<FoodEntity> {
return items.filter { it.title.contains(search, ignoreCase = true) }
}
}
data class FoodEntity(
val title: String,
val price: Int,
val category: String
)
// FoodStore returns a list of food filtered by strategy
class FoodStore(private var filterStrategy: FoodFilterStrategy) {
// we can change strategy
fun changeStrategy(strategy: FoodFilterStrategy) {
filterStrategy = strategy
}
fun foodItems(): List<FoodEntity> {
val foodItems = fetchFoodItems()
return filterStrategy.filter(foodItems)
}
private fun fetchFoodItems() =
listOf(
FoodEntity(
"Lays Potato Chips Fried Crab Flavor",
2,
"chips"
),
FoodEntity(
"Lay's Potato Chips, Classic",
3,
"chips"
),
FoodEntity(
"Dove Chocolate",
3,
"chocolate"
),
FoodEntity(
"Ritter Sport Chocolate",
4,
"chocolate"
)
)
}