-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathFacade.kt
102 lines (81 loc) · 2.5 KB
/
Facade.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package design_patterns
/**
*
* Facade is a structural design pattern that simplifies the interface to a group of interfaces
*
* with a more complex implementation
*
*/
data class GoodsEntity(
private val id: Long,
private val name: String,
private val description: String,
private val price: Double
)
class GoodsDatabase {
private val cachedGoods = mutableListOf<GoodsEntity>()
fun save(goods: List<GoodsEntity>) {
cachedGoods.addAll(goods)
}
fun read() = cachedGoods
}
class GoodsNetworkService {
fun fetch() = listOf(
GoodsEntity(
id = 1,
name = "Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software 2nd Edition",
description = "You know you don't want to reinvent the wheel, so you look to Design Patterns: the lessons learned by those who've faced the same software design problems.",
price = 41.94
)
)
}
data class CategoryEntity(
private val id: Long,
private val name: String
)
class CategoryDatabase {
private val cachedCategories = mutableListOf<CategoryEntity>()
fun save(goods: List<CategoryEntity>) {
cachedCategories.addAll(goods)
}
fun read() = cachedCategories
}
class CategoryNetworkService {
fun fetch() = listOf(
CategoryEntity(
id = 1,
name = "Books"
)
)
}
data class GoodsResult(
val goods: List<GoodsEntity>,
val categories: List<CategoryEntity>
)
// we have a group of interfaces (databases and network services)
class GoodsRepository(
private val goodsDatabase: GoodsDatabase,
private val goodsNetworkService: GoodsNetworkService,
private val categoryDatabase: CategoryDatabase,
private val categoryNetworkService: CategoryNetworkService
) {
// we need a simpler interface
fun goodsAndCategories() : GoodsResult {
val goods = goodsDatabase.read().toMutableList()
if (goods.isEmpty()) {
val networkGoods = goodsNetworkService.fetch()
goodsDatabase.save(networkGoods)
goods.addAll(networkGoods)
}
val categories = categoryDatabase.read().toMutableList()
if (categories.isEmpty()) {
val networkCategories = categoryNetworkService.fetch()
categoryDatabase.save(networkCategories)
categories.addAll(networkCategories)
}
return GoodsResult(
goods = goods,
categories = categories
)
}
}