定義
Strategy Pattern
策略模式定義了一組算法沽损,封裝各個算法灯节,使得算法之間可以相互替換。而調(diào)用者不必關(guān)心算法的具體實現(xiàn)和變化绵估。
The strategy pattern defines a family of algorithms, encapsulates each algorithm, and makes the algorithms interchangeable within that family.
UML圖
uml@2x.png
需定義一個接口類炎疆,然后各個類實現(xiàn)該接口。調(diào)用時国裳,只需定義一個接口對象形入,不需要具體的實現(xiàn)對象,即可調(diào)用缝左。
let protocol: OperationProtocol = ExecuterA()
protocol.operation()
實現(xiàn)例子
假設(shè)我們要實現(xiàn)一個繪圖程序亿遂,要畫出三角形,矩形等等渺杉,需要填充顏色蛇数,并且顏色要是可變的。比如我先畫一個藍色的三角形是越,然后再畫一個紅色的三角形耳舅。這就是種顏色選擇的策略,實現(xiàn)方可以定義好各種顏色倚评,調(diào)用者只需要選擇對應(yīng)的就好了浦徊。
代碼:
protocol ColorProtocol {
func whichColor() -> String
}
struct RedColor: ColorProtocol {
func whichColor() -> String {
return "Red"
}
}
struct GreenColor: ColorProtocol {
func whichColor() -> String {
return "Green"
}
}
protocol DrawProtocol {
func draw()
}
class Shape: DrawProtocol {
// 只需要一個顏色的接口對象,可以配置不同的顏色
var colorProtocol: ColorProtocol?
let defaultColor = "Black"
func draw() {
print("none");
}
}
// if we need green color
class Rect: Shape {
override func draw() {
if let colorProtocol = colorProtocol {
print("draw Rect with color: ", colorProtocol.whichColor());
} else {
print("draw Rect with color: ", defaultColor);
}
}
}
// if we need red color
class Tranigle: Shape {
override func draw() {
if let colorProtocol = colorProtocol {
print("draw Tranigle with color: %@", colorProtocol.whichColor());
} else {
print("draw Tranigle with color: %@", defaultColor);
}
}
}
調(diào)用如下:
var r = Rect()
r.colorProtocol = GreenColor()
r.draw()
var t = Tranigle()
t.colorProtocol = RedColor()
t.draw()
如果還需要其他顏色天梧,像上面一樣的實現(xiàn)ColorProtocol就好了盔性,不必改到原來的代碼,這就是Open Colse原則腿倚,對擴展開放纯出,對修改關(guān)閉蚯妇。