策略模式

策略模式(Strategy Pattern)

策略模式定义了一系列可互换的对象,这些对象在运行时可以互相更换。

策略这个词应该怎么理解,打个比方说,我们出门的时候会选择不同的出行方式,比如骑自行车、坐公交、坐火车、坐飞机、坐火箭等等,这些出行方式,每一种都是一个策略。

再比如我们去逛商场,商场现在正在搞活动,有打折的、有满减的、有返利的等等,其实不管商场如何进行促销,说到底都是一些算法,这些算法本身只是一种策略,并且这些算法是随时都可能互相替换的,比如针对同一件商品,今天打八折、明天满100减30,这些策略间是可以互换的。

策略模式定义了一组算法,将每个算法都封装起来,并且使它们之间可以互换。

策略模式包含3部分:

  • The object using a strategy:它经常是view controller,但在技术上也可以是任何需要可替换行为的对象。
  • strategy protocol:定义了每个策略都需要实现的方法
  • strategies:遵循strategy protocol协议的对象

使用例子:电影评分app

这是一个使用多个电影评分服务的app,比如烂番茄,IMDb和Metacritic。我们可以使用策略模式为每个电影评分服务定义一些公共的api,而不是直接在view controller中为每个服务编写代码,并可能在代码里包含复杂的if-else语句。

创建一个策略协议:

1
2
3
4
public protocol MovieRatingStrategy {
var ratingServiceName: String { get }
func fetchRating(for movieTitle: String,success: (_ rating: String, _ review: String) -> ())
}

ratingServiceName表示服务的名字,比如返回“豆瓣”。

使用fetchRatingForMovieTitle(_:success:)来异步获取电影评分。

实现多个服务

首先实现烂番茄的:

1
2
3
4
5
6
7
8
9
10
public class RottenTomatoesClient: MovieRatingStrategy {
public let ratingServiceName = "Rotten Tomatoes"
public func fetchRating(
for movieTitle: String,
success: (_ rating: String, _ review: String) -> ()) {
let rating = "95%"
let review = "It rocked!"
success(rating, review)
}
}

接着实现IMBD服务:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class IMDbClient: MovieRatingStrategy {
public let ratingServiceName = "IMDb"
public func fetchRating(
for movieTitle: String,
success: (_ rating: String, _ review: String) -> ()) {
let rating = "3 / 10"
let review = """
It was terrible! The audience was throwing rotten
tomatoes!
"""
success(rating, review)
}
}

使用策略

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
public class MoviewRatingViewController: UIViewController {
// MARK: - Properties
public var movieRatingClient: MovieRatingStrategy!
// MARK: - Outlets
@IBOutlet public var movieTitleTextField: UITextField!
@IBOutlet public var ratingServiceNameLabel: UILabel!
@IBOutlet public var ratingLabel: UILabel!
@IBOutlet public var reviewLabel: UILabel!
// MARK: - View Lifecycle
public override func viewDidLoad() {
super.viewDidLoad()
ratingServiceNameLabel.text =
movieRatingClient.ratingServiceName
}
// MARK: - Actions
@IBAction public func searchButtonPressed(sender: Any) {
guard let movieTitle = movieTitleTextField.text
else { return }
movieRatingClient.fetchRating(for: movieTitle) {
(rating, review) in
self.ratingLabel.text = rating
self.reviewLabel.text = review
}
}
}

view controller不需要知道他在使用哪个策略,它只用依赖一个协议就够了。

view controller初始化的时候必定会传入一个策略,而它并不需要知道这个策略的具体实现。

其他例子

还有一个oc的使用例子:https://www.jianshu.com/p/014df9e21c35
还有一个验证textfield输入的例子:https://blog.csdn.net/wtdask/article/details/80454852
如果代码理由有很多的if else的话,可以考虑用策略模式来优化。