美文网首页swift 文章收集
《HEAD FIRST设计模式》之策略模式

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

作者: 微微笑的蜗牛 | 来源:发表于2016-01-16 16:01 被阅读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原则,对扩展开放,对修改关闭。

相关文章

  • 策略模式(详解)

    策略模式(来自HeadFirst设计模式) 今天看了 Head First 设计模式的第一个模式,居然是策略模式,...

  • 设计模式01-策略者设计模式

    @[toc] 策略者设计模式 主要来源Head First设计模式(书) 书中定义:策略者设计模式定义了算法族,分...

  • 设计模式--策略模式

    ps:本文主要来源于Head First 设计模式(抄Head First的),如有不懂请购买原书观看。 策略模式...

  • 1.设计模式入门-策略模式

    《HEAD FIRST 设计模式》在第一章设计模式入门中介绍了策略模式(Strategy Pattern)。 定义...

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

    定义Strategy Pattern策略模式定义了一组算法,封装各个算法,使得算法之间可以相互替换。而调用者不必关...

  • Swift设计模式-目录

    推荐图书:《Head First设计模式》《大话设计模式》《设计模式之禅》, 设计模式思维导图 图形说明一切: 设...

  • 《Head First 设计模式》——策略模式

    策略模式就是将变化的那部分行为抽离出来进行封装。行为抽象成一个接口,具体的行为实现去实现这个接口。依赖接口,组合代...

  • 《Head First设计模式》-策略模式

    1.定义 策略模式定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。 2...

  • 好书推荐

    1、主要讲23种设计模式《Head First设计模式》

  • 2018-12-11

    head first html css word书籍 http权威指南 head first设计模式

网友评论

    本文标题:《HEAD FIRST设计模式》之策略模式

    本文链接:https://www.haomeiwen.com/subject/xgghkttx.html