为什么说swift是面向协议编程--草稿

为什么说swift是面向协议编程

 

public protocol ReactiveCompatible {

    /// Extended type

    associatedtype CompatibleType

 

    /// Reactive extensions.

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

 

    /// Reactive extensions.

    var rx: Reactive<CompatibleType> { get set }

}

 

extension ReactiveCompatible {

    /// 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

转载于:https://www.cnblogs.com/feng9exe/p/10497823.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值