關(guān)于常用的iOS開發(fā)中的設(shè)計模式及其應(yīng)用場景總結(jié)下:
1.單例模式
顧名思義,在程序的生命周期中只有一個這樣的實(shí)例,單例可以全局訪問,像 UserDefaults、UIApplication、NotificationCenter都是單例模式。
源碼:
class Singleton {
static let shareInstance = Singleton()
private init(){
}
}
2.委托模式
通過協(xié)議代理的方式實(shí)現(xiàn),通常用于信息的回傳,是一對一對象之間的通信。
import UIKit
//協(xié)議定義
protocol UserInfoDelegate {
func returnName(userName: String)
func returnAge(userAge: Int)
}
class UserInfoViewController: UIViewController {
var delegate: UserInfoDelegate?//協(xié)議代理
var name: String?
var age: Int?
override func viewDidLoad() {
super.viewDidLoad()
}
func infoDone(){
//調(diào)用代理方法
self.delegate?.returnName(userName: name!)
self.delegate?.returnAge(userAge: age!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
import UIKit
class FirstViewController: UIViewController,UserInfoDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//協(xié)議方法
func returnAge(userAge: Int) {
print("age is \(userAge)")
}
func returnName(userName: String) {
print("name is \(userName)")
}
}
3.觀察者模式
監(jiān)聽屬性等的變化做出相應(yīng)的改變。在Cocoa Touch 框架中,觀察者模式的應(yīng)用有兩個:通知機(jī)制和KVO機(jī)制。
通知機(jī)制:
通知機(jī)制是一對多的對象之間的通信,對某個通知感興趣的對象都可以注冊成為接收者。
swift源碼:(從ios9開始通知中心對觀察者對象進(jìn)行弱引用不需要手動從通知中心移除)
//定義通知名字常量
let notificationName = NSNotification.Name(rawValue: "updateUserInfo")
//注冊監(jiān)聽通知
NotificationCenter.default.addObserver(self, selector: #selector(reloadUserInfo(notification:)), name: notificationName, object: nil)
@objc func reloadUserInfo(notification: NSNotification){
print(notification.object!)
}
//發(fā)送通知
NotificationCenter.default.post(name: notificationName, object: ["userName": name!, "userAge": age!])