中介者模式(Mediator Pattern)是用来降低多个对象和类之间的通信复杂性。这种模式提供了一个中介类,该类通常处理不同类之间的通信,并支持松耦合,使代码易于维护。中介者模式属于行为型模式。
在MVC 框架中,其中C(控制器)就是 M(模型)和 V(视图)的中介者。我们接下来用一个搜索视图来展示中介者模式: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
67protocol HistoryView {
var isHidden: Bool { get set }
func setHistory(_ history: [String])
}
protocol HistoryRepository {
var history: [String] { get }
func addSearchTerm(_ term: String)
}
class SearchHistoryMediator: NSObject {
private let searchBar: UISearchBar
private var historyView: HistoryView
private var observasion: NSKeyValueObservation?
private let historyRepository: HistoryRepository
init(searchBar: UISearchBar, historyView: HistoryView, historyRepository: HistoryRepository) {
self.searchBar = searchBar
self.historyView = historyView
self.historyRepository = historyRepository
super.init()
self.historyView.isHidden = true
self.historyView.setHistory(historyRepository.history)
searchBar.delegate = self
observasion = searchBar.observe(\.text) { [weak self] (searchBar, _) in
self?.historyView.isHidden = searchBar.text?.isEmpty ?? false
}
}
}
extension SearchHistoryMediator: UISearchBarDelegate {
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
historyView.isHidden = false
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
historyView.isHidden = true
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
historyView.isHidden = true
if let text = searchBar.text, !text.isEmpty {
historyRepository.addSearchTerm(text)
historyView.setHistory(historyRepository.history)
searchBar.text = nil
}
searchBar.resignFirstResponder()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
historyView.isHidden = true
searchBar.resignFirstResponder()
}
}
//在控制器中使用中介者
private(set) lazy var mediator: SearchHistoryMediator = {
return SearchHistoryMediator(searchBar: searchBar, historyView: historyView, historyRepository: historyRepository)
}()
override func viewDidLoad() {
super.viewDidLoad()
_ = mediator
}
优点:降低了类的复杂度,将一对多转化成了一对一。各个类之间的解耦,减少对象之间的关联性,让每一个对象都能够独立