swift 文章收集

《HEAD FIRST设计模式》之策略模式

2016-01-16  本文已影响280人  微微笑的蜗牛

定义
Strategy Pattern
策略模式定义了一组算法,封装各个算法,使得算法之间可以相互替换。而调用者不必关心算法的具体实现和变化。
The strategy pattern defines a family of algorithms, encapsulates each algorithm, and makes the algorithms interchangeable within that family.

UML图

uml@2x.png

需定义一个接口类,然后各个类实现该接口。调用时,只需定义一个接口对象,不需要具体的实现对象,即可调用。

let protocol: OperationProtocol = ExecuterA()
protocol.operation()

实现例子
假设我们要实现一个绘图程序,要画出三角形,矩形等等,需要填充颜色,并且颜色要是可变的。比如我先画一个蓝色的三角形,然后再画一个红色的三角形。这就是种颜色选择的策略,实现方可以定义好各种颜色,调用者只需要选择对应的就好了。

代码:

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);
        }
    }
}

调用如下:

var r = Rect()
r.colorProtocol = GreenColor()
r.draw()

var t = Tranigle()
t.colorProtocol = RedColor()
t.draw()

如果还需要其他颜色,像上面一样的实现ColorProtocol就好了,不必改到原来的代码,这就是Open Colse原则,对扩展开放,对修改关闭。

上一篇下一篇

猜你喜欢

热点阅读