策略模式 Strategy Pattern

栏目: IOS · 发布时间: 5年前

内容简介:策略模式 strategy pattern 属于 behavioral pattern。Strategy pattern 定义了一系列可互换替代的对象,可以在 runtime 时设置或切换。策略模式包含以下三部分:当有两种或更多可相互代替的行为时,使用策略模式。Strategy pattern 和 Delegation pattern 很像。均依赖 protocol 而非具体对象以增加灵活性。因此,任何实现了 strategy protocol 的对象在运行时均可作为一种策略。与委托不同的是,strateg

策略模式 strategy pattern 属于 behavioral pattern。Strategy pattern 定义了一系列可互换替代的对象,可以在 runtime 时设置或切换。策略模式包含以下三部分:

策略模式 Strategy Pattern
  • 使用策略模式的对象:通常为视图控制器,也可以是任何有互换替代 (interchangeable) 需求的对象。
  • Strategy protocol:每种策略都必须遵守的协议。
  • Strategies:遵守 strategy protocol 协议的对象,相互间可互换代替。

2. 何时使用策略模式

当有两种或更多可相互代替的行为时,使用策略模式。

Strategy pattern 和 Delegation pattern 很像。均依赖 protocol 而非具体对象以增加灵活性。因此,任何实现了 strategy protocol 的对象在运行时均可作为一种策略。与委托不同的是,strategy pattern 使用一族对象。

Delegate 在运行时固定不变。例如,UITableView的dataSource和delegate设置后不需要改变。Strategy 在运行时可以相互切换。

3. Demo

Demo 是购物车结算模块。结算方式有正常价格、九折和免运费三种。

3.1 不使用 strategy pattern

更新ShoppingCartViewController.swift文件中prepare(for:sender:)方法:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    view.endEditing(false)
    
        if let destinationViewController: DetailViewController = segue.destination as? DetailViewController {
            destinationViewController.bindProperties(itemPrices:   itemPrices, checkoutType: .normal)
        }
    }
复制代码

在TotalPriceViewController.swift文件添加以下方法:

public func bindProperties(itemPrices: [Int], checkoutType: CheckoutType) {
        switch checkoutType {
        case .normal:
            finalPrice = getFinalPriceWithNormal(itemPrices: itemPrices)
            
        case .discount:
            finalPrice = getFinalPriceWithDiscount(itemPrices: itemPrices)
            
        case .freeShipping:
            finalPrice = getFinalPriceWithFreeShipping(itemPrices: itemPrices)
        }
    }
    
    private func getFinalPriceWithNormal(itemPrices: [Int]) -> Int {
        // do calculation
        
        return 90 + 75 + 20
    }
    
    private func getFinalPriceWithDiscount(itemPrices: [Int]) -> Int {
        // do calculation
        
        return Int((90 + 75) * 0.9) + 20
    }
    
    private func getFinalPriceWithFreeShipping(itemPrices: [Int]) -> Int {
        // do calculation
        
        return 90 + 75
    }
复制代码

上述代码可以根据不同枚举类型计算总价,那为什么要用 strategy pattern ?

Strategy pattern 可以让代码遵守开闭原则 (Open/Closed principle)。在面向对象编程领域中,开闭原则规定「软件中的对象、类、模块和函数等,对于扩展应该是开放的,但对于修改是封闭的」。这意味着,一个对象允许在不改变其源代码的前提下变更它的行为。该特性在产品化的环境中是特别有价值的。在这种环境中,改变源代码需要代码审查、单元测试等以确保产品质量。遵循这种原则的代码在扩展时并不发生变化,因此,无需上述过程。

目前,在 TotalPriceViewController.swift 文件添加了 enum 和所需方法,如果增加了结算方式,就需要更改 TotalPriceViewController.swift 文件中代码。但在 TotalPriceViewController.swift 文件中增加 enum 类型和 switch ,就违背了 Open/Closed principle (open for extension and close for modification) 。同时 TotalPriceViewController 掌握了太多其不必知道的内容,会使代码高度耦合、难以测试。

3.2 使用 strategy pattern

3.2.1 创建 protocol

添加 CheckoutStrategy.swift 文件,定义一项协议。在我们的示例中,该协议只有一个方法。

protocol CheckoutStrategy: class {
    func getFinalPrice(with itemPrices:[Int]) -> Int
}
复制代码

3.2.2 创建 strategies

创建三种策略,分别执行正常价格、九折和免运费结算模式:

class NormalPriceStrategy: CheckoutStrategy {
    func getFinalPrice(with itemPrices: [Int]) -> Int {
        // do calculation
        
        return 90 + 75 + 20
    }
}

class DiscountStrategy: CheckoutStrategy {
    func getFinalPrice(with itemPrices: [Int]) -> Int {
        // do calculation
        
        return Int((90 + 75) * 0.9) + 20
    }
}

class FreeShippingStrategy: CheckoutStrategy {
    func getFinalPrice(with itemPrices: [Int]) -> Int {
        // do calculation
        
        return 90 + 75
    }
}
复制代码

可以看到,每个类均遵守 CheckoutStrategy 协议,但协议中方法实现方式有所不同,每个类代表一种策略。

3.2.3 使用策略模式的对象

更新 ShoppingCartViewController.swift 文件中 prepare(for:sender:) 方法,使用 strategy pattern 结算:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        view.endEditing(false)
        
        if let destinationViewController: TotalPriceViewController = segue.destination as? TotalPriceViewController {
            destinationViewController.bindProperties(itemPrices: itemPrices, checkoutStrategy: NormalPriceStrategy())
//            destinationViewController.bindProperties(itemPrices: itemPrices, checkoutStrategy: DiscountStrategy())
//            destinationViewController.bindProperties(itemPrices: itemPrices, checkoutStrategy: FreeShippingStrategy())
        }
    }
复制代码

同时在 TotalPriceViewController.swift 文件添加以下方法:

public func bindProperties(itemPrices:[Int], checkoutStrategy: CheckoutStrategy) {
        finalPrice = checkoutStrategy.getFinalPrice(with: itemPrices)
    }
复制代码

最后,project navigator 目录如下:

策略模式 Strategy Pattern
现在,添加、修改结算模式时,只需要增加遵守 CheckoutStrategy

协议的策略,修改结算策略即可。

4. 更多示例

下面示例也适合使用 strategy pattern 。

4.1 选择行程

旅行 app 提供单程、往返两种购票模式。当进入日历时,根据单程、往返来决定采取哪种选择日期策略。例如,如果是往返,则返回日期必须晚于出发日期。

策略模式 Strategy Pattern

因此,我们有两种选择策略,当打开日历时指定所采用的策略:

protocol CalendarSelectionStrategy {
    func calendar(_ calendar: CalendarView, didSelect date: Date)
}

class OneWaySelectionStrategy: CalendarSelectionStrategy {
    func calendar(_ calendar: CalendarView, didSelect date: Date) {
        // One way selection logic
    }
}

class ReturnWaySelectionStrategy: CalendarSelectionStrategy {
    func calendar(_ calendar: CalendarView, didSelect date: Date) {
        // Return selection logic
    }
}

// Use
showCalendar(usingSelectionStrategy: OneWaySelectionStrategy())
复制代码

4.2 表格验证

App 内表格内容有多种文本类型,如文字、数字、密码、手机号码等,每种类型有不同验证方式。我们可以为每种类型定义一种验证策略,这样每个文本框就能知道如何验证其内容是否符合要求。

protocol ValidateStrategy {
    func validate() -> Bool
}
复制代码

4.3 更换武器

在游戏中,用户会经常更换武器。武器的触发操作方式是一样的,但每种武器都有自己的射击方式。用户无需用知道具体射击细节,武器本身知道即可。


以上所述就是小编给大家介绍的《策略模式 Strategy Pattern》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Modeling the Internet and the Web

Modeling the Internet and the Web

Pierre Baldi、Paolo Frasconi、Padhraic Smyth / Wiley / 2003-7-7 / USD 115.00

Modeling the Internet and the Web covers the most important aspects of modeling the Web using a modern mathematical and probabilistic treatment. It focuses on the information and application layers, a......一起来看看 《Modeling the Internet and the Web》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具