爲何說swift是面向協議編程--草稿

爲何說swift是面向協議編程程序員

 

public protocol ReactiveCompatible {編程

    /// Extended typeswift

    associatedtype CompatibleTypethis

 

    /// Reactive extensions.接口

    static var rx: Reactive<CompatibleType>.Type { get set }ci

 

    /// Reactive extensions.get

    var rx: Reactive<CompatibleType> { get set }it

}io

 

extension ReactiveCompatible {class

    /// Reactive extensions.

    public static var rx: Reactive<Self>.Type {

        get {

            return Reactive<Self>.self

        }

        set {

            // this enables using Reactive to "mutate" base type

        }

    }

 

    /// Reactive extensions.

    public var rx: Reactive<Self> {

        get {

            return Reactive(self)

        }

        set {

            // this enables using Reactive to "mutate" base object

        }

    }

}

 

protocol Response {

    /// The task metrics containing the request / response statistics.

    var _metrics: AnyObject? { get set }

    mutating func add(_ metrics: AnyObject?)

}

 

 

 

 

 

其實像 Ruby 中的 Mix-in 或 Trait能夠實現相似的功能,這裏不展開討論了。

固然會有人說,面向協議編程,這裏的 protocol 不就是 Java 中的 interface 嗎,對,也不對。Java 中的 interface,更多的功能是處理類型信息,更像是多態的效果,然而並無提供代碼的複用機制,由於擁有相同接口的不一樣的類,即便他們的接口實現都相同,也必須同時實現這個接口,因而,重複代碼又出現了!

在 Swift 2.0 以後,咱們能夠使用 extension 爲 protocol 添加默認的實現,也就是說,在大多數狀況下,咱們使用這種低耦合的方式,讓你的類站出來講,我要遵循 XXX 協議,而後,就完成了!

 

http://www.futantan.com/2016/03/03/程序員的懶惰與面向協議編程-POP/

 

"A protocol defines a blueprint of methods, properties… The protocol can then be adopted by a class, structure, or enumeration" - Apple

相關文章
相關標籤/搜索