Swift面向协议编程(POP)的一些Tips

移动开发
协议最常见的用法莫过于进行代理传值,这就是委托模式。常用的应用场景有:controller中自定义了一个view,view中又添加了一个自定义view。在自定义的view中如果有些函数或者属性需要到controller中去调用,委托模式的做法就是规定一个协议,让controller去遵守一个协议并提供实现。

一、委托模式

1、使用过程

协议最常见的用法莫过于进行代理传值,这就是委托模式。常用的应用场景有:controller中自定义了一个view,view中又添加了一个自定义view。在自定义的view中如果有些函数或者属性需要到controller中去调用,委托模式的做法就是规定一个协议,让controller去遵守一个协议并提供实现,那么在自定义view中就能使用协议中的方法。

Swift面向协议编程(POP)的一些Tips

举个例子,现在想在一个controller中添加一个自定义view,可以实现点击view中按钮更改controller中label的值。简单的代码如下:

自定义view 

  1. //SelectTabbar.swift 
  2. @objc protocol SelectTabbarDelegate { 
  3.     func changeLabel(_ str: String) 
  4.  
  1. //SelectTabbar.swift 
  2.  class SelectTabbar: UIView { 
  3.     var keywords : [String]? 
  4.     var buttons : [UIButton]? 
  5.     weak public var delegate : SelectTabbarDelegate? 
  6.       
  7.     init(frame: CGRect,keywords:[String]) { 
  8.         super.init(frame: frame) 
  9.         self.keywords = keywords 
  10.         renderView() 
  11.     } 
  12.       
  13.     required init?(coder aDecoder: NSCoder) { 
  14.         fatalError("init(coder:) has not been implemented"
  15.     } 
  16.       
  17.     override func layoutSubviews() { 
  18.         super.layoutSubviews() 
  19.     } 
  20.       
  21.     private func renderView(){ 
  22.         buttons = keywords?.enumerated().map({ (index,key) ->UIButton in 
  23.             let buttonWidth = kScreenWidth/CGFloat((keywords?.count)!) 
  24.             let button = UIButton.init(frame: CGRect.init(x: CGFloat(index)*buttonWidth, y: 0, width: buttonWidth, height: 50)) 
  25.             button.setTitle(keyfor: .normal) 
  26.             button.setTitleColor(UIColor.blue, for: .normal) 
  27.             button.backgroundColor = UIColor.gray 
  28.             button.tag = index 
  29.             button.addTarget(self, action: #selector(tapButton(sender:)), for: .touchUpInside) 
  30.             addSubview(button) 
  31.             return button 
  32.         }) 
  33.     } 
  34.       
  35.     @objc func tapButton(sender: UIButton){ 
  36.         delegate?.changeLabel(keywords![sender.tag]) 
  37.     } 
  38.       

controller: 

  1. class TestViewController: UIViewController,SelectTabbarDelegate { 
  2.     lazy var label : UILabel = { 
  3.         var label = UILabel(frame: CGRect.init(x: 50, y: 200, width: 100, height: 30)) 
  4.         label.text = labelStr 
  5.         label.backgroundColor = UIColor.red 
  6.         return label 
  7.     }() 
  8.       
  9.     private var labelStr : String? { 
  10.         didSet{ 
  11.             label.text = labelStr 
  12.         } 
  13.     } 
  14.       
  15.     override func viewDidLoad() { 
  16.         super.viewDidLoad() 
  17.         view.backgroundColor = .white 
  18.         view.addSubview(label) 
  19.         setupSelectTabbar() 
  20.     } 
  21.       
  22.     func setupSelectTabbar(){ 
  23.         let selectTabbar = SelectTabbar(frame: CGRect.init(x: 0, y: kNavigationHeightAndStatuBarHeight, width: kScreenWidth, height: 50),keywords:["aa","bb"]) 
  24.         selectTabbar.delegate = self 
  25.         view.addSubview(selectTabbar) 
  26.     } 
  27.     func changeLabel(_ str: String) { 
  28.         labelStr = str 
  29.     } 
  30.       

这样就能比较清楚的表明自己的逻辑。否则,如果要在view操作controller的内容,则需要在外部操作controller的实例,这就造成一个问题,就是无法操作实例中的私有属性和私有方法(虽然iOS是一门动态语言,不存在绝对的私有,但是谁会去一直去使用runtime来进行操作呢)。

2、注意点

在 ARC 中,对于一般的 delegate,我们会在声明中将其指定为 weak,在这个 delegate 实际的对象被释放的时候,会被重置回 nil。这可以保证即使 delegate 已经不存在时,我们也不会由于访问到已被回收的内存而导致崩溃。ARC 的这个特性杜绝了 Cocoa 开发中一种非常常见的崩溃错误,说是救万千程序员于水火之中也毫不为过。

在 Swift 中我们当然也会希望这么做。但是当我们尝试书写这样的代码的时候,编译器不会让我们通过:

  1. 'weak' cannot be applied to non-class type 

原因:这是因为 Swift 的 protocol 是可以被除了 class 以外的其他类型遵守的,而对于像 struct 或是 enum 这样的类型,本身就不通过引用计数来管理内存,所以也不可能用 weak 这样的 ARC 的概念来进行修饰。

两种解决方法:

  1. 使用@objc
  2. 声明类类型专属协议。通过添加 class 关键字来限制协议只能被类类型遵循,而结构体或枚举不能遵循该协议。class 关键字必须***个出现在协议的继承列表中,在其他继承的协议之前
  • protocol SelectTabbarDelegate : class

二、AOP编程思想的运用

首先我们理解下AOP的含义。

  • In computing, aspect-oriented programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. It does so by adding additional behavior to existing code (an advice) without modifying the code itself, instead separately specifying which code is modified via a “pointcut” specification, such as “log all function calls when the function’s name begins with ‘set’”. This allows behaviors that are not central to the business logic (such as logging) to be added to a program without cluttering the code, core to the functionality. AOP forms a basis for aspect-oriented software development.

在swift简单来说,就是利用协议去切入某些代码中,将额外的功能单独出来而不产生耦合,可以将这些与主逻辑关系不大的代码统一放到一起。

常用的场景:日志记录,性能统计,安全控制,事务处理,异常处理等等。

接上面的例子,我们需要在打开TestViewController的时候统计一次,点击两个按钮的时候也进行统计,统计的内容由identifer进行区分。

我们先建立一个Statistician.swift 来存放我们的统计逻辑。(模拟实现)

申明一个StatisticianProtocal协议并提供他的默认实现。 

  1. import Foundation 
  2. enum LogIdentifer:String { 
  3.     case button1 = "button1" 
  4.     case button2 = "button2" 
  5.     case testViewController = "testViewController" 
  6.   
  7. protocol StatisticianProtocal { 
  8.     func statisticianLog(fromClass:AnyObject, identifer:LogIdentifer) 
  9.     func statisticianUpload(fromClass:AnyObject, identifer:LogIdentifer) 
  10.     //用一个尾随闭包来扩展功能 
  11.     func statisticianExtension(fromClass:AnyObject, identifer:LogIdentifer, extra:()->()) 
  12.   
  13. extension StatisticianProtocal{ 
  14.     func statisticianLog(fromClass:AnyObject, identifer:LogIdentifer) { 
  15.         print("statisticianLog--class:\(fromClass) from:\(identifer.rawValue)"
  16.     } 
  17.       
  18.     func statisticianUpload(fromClass:AnyObject, identifer:LogIdentifer) { 
  19.         print("statisticianUpload--class:\(fromClass) from:\(identifer.rawValue)"
  20.     } 
  21.       
  22.     func statisticianExtension(fromClass:AnyObject, identifer:LogIdentifer, extra:()->()){ 
  23.         extra() 
  24.     } 
  25.   
  26. class Statistician: NSObject { 
  27.   

接下来在任何需要统计的类里面,我们让这个类去遵守这个协议,然后在需要的地方调用协议中的方法即可。如果在某个特定的类中需要调用的方法略有不同,重写协议中的方法即可。 

  1. class SelectTabbar: UIView,StatisticianProtocal { 
  2.     var keywords : [String]? 
  3.     var buttons : [UIButton]? 
  4.     weak public var delegate : SelectTabbarDelegate? 
  5.       
  6.     init(frame: CGRect,keywords:[String]) { 
  7.         super.init(frame: frame) 
  8.         self.keywords = keywords 
  9.         renderView() 
  10.         //进行一次统计 
  11.         operateStatistician(identifer: .testViewController) 
  12.     } 
  13.       
  14.     required init?(coder aDecoder: NSCoder) { 
  15.         fatalError("init(coder:) has not been implemented"
  16.     } 
  17.       
  18.       
  19.     override func layoutSubviews() { 
  20.         super.layoutSubviews() 
  21.     } 
  22.       
  23.     private func renderView(){ 
  24.         buttons = keywords?.enumerated().map({ (index,key) ->UIButton in 
  25.             let buttonWidth = kScreenWidth/CGFloat((keywords?.count)!) 
  26.             let button = UIButton.init(frame: CGRect.init(x: CGFloat(index)*buttonWidth, y: 0, width: buttonWidth, height: 50)) 
  27.             button.setTitle(keyfor: .normal) 
  28.             button.setTitleColor(UIColor.blue, for: .normal) 
  29.             button.backgroundColor = UIColor.gray 
  30.             button.tag = index 
  31.             button.addTarget(self, action: #selector(tapButton(sender:)), for: .touchUpInside) 
  32.             addSubview(button) 
  33.             return button 
  34.         }) 
  35.     } 
  36.       
  37.     @objc func tapButton(sender: UIButton){ 
  38.         //进行一次统计 
  39.         switch sender.tag { 
  40.           case 0:operateStatistician(identifer: .button1) 
  41.           default:operateStatistician(identifer: .button2) 
  42.         } 
  43.         delegate?.changeLabel(keywords![sender.tag]) 
  44.     } 
  45.       
  46.     func operateStatistician(identifer:LogIdentifer){ 
  47.         statisticianLog(fromClass: self, identifer: identifer) 
  48.         statisticianUpload(fromClass: self, identifer: identifer) 
  49.         statisticianExtension(fromClass: self, identifer: identifer) { 
  50.             print("extra: in SelectTabbar class"
  51.         } 
  52.     } 
  53.       

以上代码实现了三处统计的逻辑,而不用把统计的逻辑写入controller文件中,降低了功能上的耦合度。

三、用来代替extension,增强代码可读性

使用扩展,可以很方便的为一些继承它的子类增添一些函数。这就带来一个问题,就是所有的子类都拥有了这个方法,但是方法的本身可能不明确,或者是只是想让少数子类来使用这个方法。这时候可以使用协议来代替extension。 

  1. //定义了一个Shakable协议,遵守这个协议的类即可使用里面的方法,并为该方法提供一个默认的实现 
  2. //where Self:UIView表明了只有uiview的子类可以遵守这个协议 
  3. protocol Shakable { 
  4.     func shakeView() 
  5.   
  6. extension Shakable where Self:UIView{ 
  7.     func shakeView(){ 
  8.         print(Self.self) 
  9.     } 

这时候可以让某个子类来遵守协议。例如刚才上面的例子。

  1. class SelectTabbar: UIView,Shakable 

如果不在类中重新实现这个方法,则可以实现默认的方法。这个意思表明,SelectTabbar类的子类是遵守Shakable协议的,间接等于SelectTabbar():Shakable?。这样我们就可以愉快的让SelectTabbar对象去使用这个方法。(Self关键字只能用在协议或者类中,表示当前类,可作为返回值使用)。

一旦不想让某个子类使用shakeView()方法,很简单,只要把class SelectTabbar: UIView,Shakable中的Shakable协议干掉即可。

其他实践:

利用AOP去分离tableview的数据源和事件源的方法,可以单独处理里面的逻辑,使tableview的代理方法不显得那么冗余。

总结

关于协议,还有很多种用法。以上是目前比较常用的场景。日后开发中如果发现协议在其他地方中有更好的应该,将会更新本文

 

责任编辑:未丽燕 来源: peipeiblog
相关推荐

2023-10-09 08:14:10

Helm管理应用

2013-07-02 10:18:20

编程编程策略

2013-07-02 09:43:02

编程策略

2010-06-09 17:13:12

IPv6协议路由协议

2021-10-13 07:48:23

Options模式编程

2010-08-05 13:54:36

NFS协议

2021-04-09 10:26:43

Python编程技术

2018-06-08 08:50:35

编程语言并发编程

2011-09-13 09:41:59

Python

2011-08-31 10:54:25

Java性能

2012-02-16 08:19:03

2012-04-05 13:24:30

2015-08-04 08:56:14

swift子类

2015-09-15 10:40:41

Swift2.0MVVM

2010-09-17 15:41:46

网络协议分析软件

2016-12-12 15:22:41

编程

2022-07-30 23:41:53

面向过程面向对象面向协议编程

2009-11-23 13:44:33

PHP5面向对象

2015-03-30 11:21:27

编程编程反思

2020-12-04 09:11:45

Python加密文件爆破字典
点赞
收藏

51CTO技术栈公众号