浅谈编程思想
一. 常见的编程思想
面向过程:以过程为中心的编程思想。分析出解决问题所需要的步骤,然后用函数把这些步骤一步一步实现,使用的时候一个一个依次调用。
面向对象(OOP):把事物抽象成对象,然后给对象赋一些属性和方法,然后让每个对象去执行自己的方法。(*封装,继承,多态)
链式编程:每个方法返回一个”返回值为自身且带有一个参数项“的Block (或直接返回自身),形成Block串联,也就是所谓的链式编程。(eg: Monsary, SnapKit )
函数式编程: 思想上,函数式编程可谓博大精深,建议看这篇文章了解: 传送门 形式上,函数是一等公民,常见函数(闭包)作为参数或返回值传递、闭包嵌套、函数组合等形式。(eg: map, filter, reduce等高阶函数,Monsary, SnapKit 等等)
响应式编程:对于输入的变动加以监听,响应式地,每次产生对应的输出。(eg: 通知,kvo)
面向协议编程(POP):面向抽象和具象而不是具体的某个类。
二. 链式编程 核心:函数返回值为自身(或者一个返回自身的Block)。
1.实现 1 2 3 4 5 6 7 8 9 10 11 12 func sub (num: Double) -> Calculator { result -= num; return self } func bk_add () -> (Double )->Calculator { return { (number) -> Calculator in self .result += number return self } }
2.调用 1 2 3 4 func testA () { self .calculator.add(num: 2 ).sub(num: 1 ).multiply(num: 1 ).divide(num: 1 ) print ("\(#function) in 结果: \(self.calculator.result)" ) }
三. 函数式编程 核心:方法(函数)的参数或者返回值为 函数 (Block)
1.实现 1 2 3 4 5 6 7 8 9 10 11 12 13 static func makeOperation (closure:(Calculator) ->Void ) -> Double { let calculator = Calculator () closure(calculator) return calculator.result } func testMap () { let numbers = [1 ,2 ,3 ] let mapNumbers = numbers.map { (number) -> String in return "\(number + 2)" } print (mapNumbers) }
2.使用 1 2 3 4 5 6 func testC () { let result = Calculator .makeOperation { maker in maker.add(num: 10 ).sub(num: 5 ).multiply(num: 1 ).divide(num: 2 ) } print ("\(#function) in 结果: \(result)" ) }
四. 响应式编程 核心:建立从’’输入 -> 输出’’的通道 ,每次输入响应式地产出对应的输出
1.实现 1 2 3 4 5 6 7 8 9 10 11 12 13 func addNotification () { NotificationCenter .default .addObserver(self , selector: #selector(doSomeThings(notification:)), name: NSNotification .Name (rawValue:"MyNotification" ), object: nil ) } func postNotification () { NotificationCenter .default .post(name: NSNotification .Name (rawValue:"MyNotification" ), object: nil , userInfo: ["Info" :"AAA" ]) } @objc func doSomeThings (notification:NSNotification) { if let info = notification.userInfo?["Info" ] { print (info) } }
2.使用
五. 面向协议编程 核心:Don’t start with a class. Start with a protocol. — WWDC 2015
1.实现 1 2 3 4 5 6 7 @objc protocol CalculatorProtocol { var result:Double { get set } @objc optional func add (num: Double) -> CalculatorProtocol @objc optional func sub (num: Double) -> CalculatorProtocol @objc optional func multiply (num: Double) -> CalculatorProtocol @objc optional func divide (num: Double) -> CalculatorProtocol }
2.使用 1 2 3 4 5 6 class MCObject :CalculatorProtocol { var result: Double = 0.0 func testCalculator () { self .add(num: 1 ).sub(num: 2 ).divide(num: 3 ).multiply(num: 4 ) } }
六.相关框架 1.ReactiveCocoa https://github.com/ReactiveCocoa/ReactiveCocoa
2.RXSwift https://www.jianshu.com/p/f7d89f969ad7
https://github.com/ReactiveX/RxSwift
</div>