Swift之Protocol

作者: 践行者 | 来源:发表于2017-05-23 13:22 被阅读53次
u=Protocol.jpg

1.什么是Protocol

官方给出了如下解释:

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.
The Swift Programming Language Guide by Apple

协议提供了一系列行为规范信息,允许遵守它的类型可以做什么,即强调了what an object does.;而Struct && Class 对具体事物的抽象,强调了 what an object is

在面向对象设计时,继承分为两种:接口继承 and 类继承,让我们来看一下两者区别:

2.Protocols vs. Subclassing

2.1 Subclassing

<pre>
class Parent {
//属性
var property: String?
//方法
func function() {
print("My Name is function")
}
//构造
init() {

}
//析构
deinit {
    
}

}

class Child : Parent {
}
let child = Child()
child.function();
</pre>

从上面代码中,看出Subclassing 定义了parent / child 关系 ,Child作为Parent的子类,继承了Parent的"血统"(属性,方法,初始化等等),当然Child对Parent的特性进行自我改造,升级,所谓的重写 or 覆盖

2.2 Protocols

Subclassing存在一个缺陷,比如:
<pre>
class Animal {
func makeSound() {}
}
</pre>
动物的叫声各式各样,如果Class Dog : Animal 就需要实现makeSound(),如果忘了呢?

u=沃美啊美.jpg

轻则bug,重则Crash.

<pre>
protocol Sound {
func makeSound() ;
}
</pre>
protocol 并不关心what the object really is,我们只关心谁实现了我们的要求~

最后简单,提一嘴: 协议可以模拟实现多继承,另外swift中Extention可以默认实现协议方法~

3.总结

 记住:面向协议开发并不是为了替代OOP,而是为了弥补OOP的不足,在开发中不要掉入 唯一编程方法陷阱中~ 我们应该学会灵活,分析每一种方案以及场景的应用~

相关文章

网友评论

    本文标题:Swift之Protocol

    本文链接:https://www.haomeiwen.com/subject/hhmwxxtx.html