iOS开发攻城狮的集散地程序猿阵线联盟-汇总各类技术干货程序员

设计模式(Swift) - 3.观察者模式、建造者模式

2018-07-01  本文已影响38人  Dariel

上一篇 设计模式(Swift) - 2.单例模式、备忘录模式和策略模式中讲了三种常见的设计模式.

1. 观察者模式(Observer Pattern)

1. 观察者模式概述

观察者模式: 一个对象的变化,能够被另一个对象知道.
本文除了介绍基于Runtime的KVO实现及其原理,还会自己动手去现实一套观察者模式,毕竟在swift中使用Runtime并不被推荐.


2. 基于OC Runtime的观察者模式实现

1. 实现一个继承自NSObject的可观察对象
 // @objcMembers 为了给类中每个属性添加 @objc 关键词,
@objcMembers public class KVOUser: NSObject {
    dynamic var name: String

    public init(name: String) {
        self.name = name
    }
}

@objcMembers 为了给类中每个属性添加 @objc 关键词,在swift4中继承NSObject的子类的属性不会暴露给OC的Runtime,所以只能手动添加

swift本身是门静态语言,添加@objc 关键词是为了让属性具有动态特性,可以动态的生成set和get方法,因为KVO就需要去操作set方法.

    // 注意kvoObserver的生命周期
    var kvoObserver: NSKeyValueObservation?
    let kvoUser = KVOUser(name: "Dariel")

    // 监听kvoUser name属性的变化
    kvoObserver = kvoUser.observe(\.name, options: [.initial, .new]) {
            (user, change) in
            print("User's name is \(user.name)")
    }

第一个参数是路径,这边是简略写法.name, swift会自己转成全路径; options是 NSKeyValueObservingOptions, 这边传入的表示初始化的值和新的值

2. 使用继承自NSObject的可观察对象
 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
      kvoUser.name = "John"
}

在任何地方改变kvoUser对象的name属性,kvoObserver的observe方法都会回调.

3. OC Runtime的观察者模式实现原理

那么KVO是怎样实现对对象属性的监听的呢?
当给一个对象添加KVO之后,OC会通过Runtime将这个对象的isa指针指向(未设定KVO的对象的isa指针指向该对象的类对象)自己定义的一个原类的子类类对象(NSKVONotifying_xxx),这个子类类对象的isa指针指向原来对象的类对象,并调用这个类对象中的set方法,然后去通知监听器哪些值发生了改变.


KVO具体的实现原理

在Swift4中,并没有在语言层级上支持KVO,如果要使用需要导入Foundation和被观察对象必须继承自NSObject,这种实现方式显然不够优雅.

4. 实现一个不基于Runtime的观察者模式

KVO的观察者模式本质上还是通过拿到属性的set方法去搞事情,基于这样的原理我们可以自己实现.直接贴代码,新建一个Observable的swift文件

public class Observable<Type> {
    
    // MARK: - Callback
    fileprivate class Callback {
        fileprivate weak var observer: AnyObject?
        fileprivate let options: [ObservableOptions]
        fileprivate let closure: (Type, ObservableOptions) -> Void
        
        fileprivate init(
            observer: AnyObject,
            options: [ObservableOptions],
            closure: @escaping (Type, ObservableOptions) -> Void) {
            
            self.observer = observer
            self.options = options
            self.closure = closure
        }
    }
    
    // MARK: - Properties
    public var value: Type {
        didSet {
            removeNilObserverCallbacks()
            notifyCallbacks(value: oldValue, option: .old)
            notifyCallbacks(value: value, option: .new)
        }
    }
    
    private func removeNilObserverCallbacks() {
        callbacks = callbacks.filter { $0.observer != nil }
    }
    
    private func notifyCallbacks(value: Type, option: ObservableOptions) {
        let callbacksToNotify = callbacks.filter { $0.options.contains(option) }
        callbacksToNotify.forEach { $0.closure(value, option) }
    }
    
    // MARK: - Object Lifecycle
    public init(_ value: Type) {
        self.value = value
    }
    
    // MARK: - Managing Observers
    private var callbacks: [Callback] = []
    
    
    /// 添加观察者
    ///
    /// - Parameters:
    ///   - observer: 观察者
    ///   - removeIfExists: 如果观察者存在需要移除
    ///   - options: 被观察者
    ///   - closure: 回调
    public func addObserver(
        _ observer: AnyObject,
        removeIfExists: Bool = true,
        options: [ObservableOptions] = [.new],
        closure: @escaping (Type, ObservableOptions) -> Void) {
        
        if removeIfExists {
            removeObserver(observer)
        }
        
        let callback = Callback(observer: observer, options: options, closure: closure)
        callbacks.append(callback)
        
        if options.contains(.initial) {
            closure(value, .initial)
        }
    }
    
    public func removeObserver(_ observer: AnyObject) {
        callbacks = callbacks.filter { $0.observer !== observer }
    }
}

// MARK: - ObservableOptions
public struct ObservableOptions: OptionSet {
    
    public static let initial = ObservableOptions(rawValue: 1 << 0)
    public static let old = ObservableOptions(rawValue: 1 << 1)
    public static let new = ObservableOptions(rawValue: 1 << 2)
    
    public var rawValue: Int
    
    public init(rawValue: Int) {
        self.rawValue = rawValue
    }
}

使用:

public class User {
    // 被观察的属性需要是Observable类型
    public let name: Observable<String>
    public init(name: String) {
        self.name = Observable(name)
    }
}
// 用来管理观察者
public class Observer {}

var observer: Observer? // 当observer置为nil的时候,可观察对象会自动释放.
let user = User(name: "Made")
observer = Observer()
user.name.addObserver(observer!, options: [.new]) { name, change in     
    print("name:\(name), change:\(change)")                        
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {        
    user.name.value = "Amel"
}

注意: 在使用过程中,如果改变value, addObserver方法不调用,很有可能是Observer对象已经被释放掉了.

5. 观察者模式的使用场景

观察者模式一般用在MVC模式中,控制器需要监听某个模型属性的改变,而模型不需要知道控制器的类型,因此多个控制器可以监听一个模型对象.

2. 建造者模式(Buidler Pattern)

1. 建造者模式概述

建造者模式可以一步步分解复杂业务场景的实现过程.


1. 建造者模式举例

1. Product
// MARK: - Product
public struct Person {
    public let area: Area
    public let character: Character
    public let hobby: Hobby
}
extension Person: CustomStringConvertible {
    public var description: String {
        return area.rawValue
    }
}
public enum Area: String { // 来自区域
    case ShangHai
    case ShenZhen
    case HangZhou
    case Toronto
}
public struct Character: OptionSet { // 性格
    
    public static let independent = Character(rawValue: 1 << 1) // 2
    public static let ambitious = Character(rawValue: 1 << 2) // 4
    public static let outgoing = Character(rawValue: 1 << 3) // 8
    public static let unselfish = Character(rawValue: 1 << 4) // 16
    public static let expressivity = Character(rawValue: 1 << 5) // 32

    public let rawValue: Int
    public init(rawValue: Int) {
        self.rawValue = rawValue
    }
}
public struct Hobby: OptionSet { // 爱好
    
    public static let mountaineering = Hobby(rawValue: 1 << 1)
    public static let boating = Hobby(rawValue: 1 << 2)
    public static let climbing = Hobby(rawValue: 1 << 3)
    public static let running = Hobby(rawValue: 1 << 4)
    public static let camping = Hobby(rawValue: 1 << 5)
    
    public let rawValue: Int
    public init(rawValue: Int) {
        self.rawValue = rawValue
    }
}

Person中定义了三个属性,area地区,character性格,hobby爱好,其中地区只能是一个值,性格和爱好可以支持多个值.Character和Hobby可以通过传入一个值,设置多个值.

2. Builder
// MARK: - Builder
public class PersonStatistics {
    public private(set) var area: Area = .HangZhou
    public private(set) var characters: Character = []
    public private(set) var hobbys: Hobby = []
    
    private var outOfAreas: [Area] = [.Toronto]
    
    public func addCharacter(_ character: Character) {
        characters.insert(character)
    }
    
    public func removeCharacter(_ character: Character) {
        characters.remove(character)
    }
    
    public func addHobby(_ hobby: Hobby) {
        hobbys.insert(hobby)
    }
    
    public func removeHobby(_ hobby: Hobby) {
        hobbys.remove(hobby)
    }
    
    public func setArea(_ area: Area) throws {
        guard isAvailable(area) else { throw Error.OutOfArea }
        self.area = area
    }
    
    public func build() -> Person {
        return Person(area: area, character: characters, hobby: hobbys)
    }
    
    public func isAvailable(_ area: Area) -> Bool {
        return !outOfAreas.contains(area)
    }
    
    public enum Error: Swift.Error {
        case OutOfArea
    }
}

通过builder统一对Product进行管理,设置完数据之后再去创建Person对象.

3. Director
public class ManagerStatistics {

    public func createLiLeiData() throws -> Person {
        let builder = PersonStatistics()
        try builder.setArea(.HangZhou)
        builder.addCharacter(.ambitious)
        builder.addHobby([.climbing, .boating, .camping])
        return builder.build()
    }
    
    public func createLucyData() throws -> Person {
        let builder = PersonStatistics()
        try builder.setArea(.Toronto)
        builder.addCharacter([.ambitious, .independent, .outgoing])
        builder.addHobby([.boating, .climbing, .camping])
        return builder.build()
    }
}

通过Director去设置builder中的数据.

 let manager = ManagerStatistics()
        
 if let Lucy = try? manager.createLucyData() {
     print(Lucy.description)
     print(Lucy.character)
     print(Lucy.hobby)
 }else {
     print("Out of area here")
 }
        
 if let Lilei = try? manager.createLiLeiData() {
     print(Lilei.description)
     print(Lilei.character)
     print(Lilei.hobby)
 }

2. 建造者模式的使用注意

建造者模式是用在创造比较复杂的Product,这个Product需要设置很多值,而这用构造器又比较麻烦的情况下.如果Product比较简单,那用构造器就好了.

3. 总结

本篇主要讲了用来对对象监听的观察者模式和用在创建和管理复杂对象场景下的建造者模式.

示例代码

参考:
The Swift Programming Language (Swift 4.1)
Objective-C编程之道
Design Patterns by Tutorials

如有疑问,欢迎留言 :-D

上一篇下一篇

猜你喜欢

热点阅读