这个我们在开发中应该算是非常常用的模式了,封装不同的算法。
Kingfisher中使用到的
protocol RetryStrategy {
func retry(context: RetryContext, retryHandler: @escaping (RetryDecision) -> Void)
}
public struct DelayRetryStrategy: RetryStrategy {
func retry(context: RetryContext, retryHandler: @escaping (RetryDecision) -> Void) {
// 算法的具体实现
}
}
- 项目中使用,重构
if else代码 比如我们项目中openurl的处理
func openurl(_ url: String) {
if (url == "a") {
nav.push(to: vca)
} else if (url == "b") {
nav.push(to: vcb)
} else if (url == "c") {
nav.push(to: vcc)
} else if (url == "d") {
nav.push(to: vcd)
} else if (url == "e") {
nav.push(to: vce)
}
...
}
重构
protocol Push {
func push(_ nav: UIViewController)
}
struct PushA {
func push(_ nav: UIViewController) {
nav.push(to: vca)
}
}
...
struct Factory {
static func getStrategy(with url: String) {
if (url == "a") {
return PushA()
}
...
}
}
func openurl(_ url: String) {
let strategy = Factory.getStrategy(with: url)
strategy.push(nav)
}
问: if else 什么时候需要用到策略重构呢?
答:后续会有新的策略,并且这个策略里面的算法代码较长(这个是必要条件,不然的话可能用枚举,或者直接使用 if else 就是可以的)。
除了使用策略模式还有其他的重构方式吗?
可以使用状态模式或者卫语句。
卫语句就是把错误提前返回了,不要用 if else if 这样的嵌套了。在 swift 里面我们直接使用 guard 就可以了。
- 我们在
array用到的排序其实也是策略模式,这个算法我们直接使用闭包传递进去了。
array.sorted(by: <)
array.sorted { $0.age < $1.age }