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

定义
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原则,对扩展开放,对修改关闭。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,914评论 18 139
  • 🎉 对设计模式的极简说明!🎉 这个话题可以轻易让任何人糊涂。现在我尝试通过用 最简单 的方式说明它们,来让你(和我...
    月球人simon阅读 1,121评论 1 2
  • [Java策略模式(Strategy模式) 之体验] public class Client { } 测试输出结果...
    坚持编程_lyz阅读 255评论 0 0
  • 设计模式系列文章 《iOS设计模式(1)简单工厂模式》《iOS设计模式(2)工厂模式》《iOS设计模式(3)适配器...
    leehoo阅读 12,759评论 14 50
  • ios开发学习中,经常弄不清楚ios的开发模式,今天我们就来进行简单的总结和探讨~(一)代理模式应用场景:当一个类...
    贝勒老爷阅读 1,320评论 1 8