iOS中的設(shè)計模式(swift4版)

關(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!])

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 設(shè)計模式概述 在學(xué)習(xí)面向?qū)ο笃叽笤O(shè)計原則時需要注意以下幾點(diǎn):a) 高內(nèi)聚、低耦合和單一職能的“沖突”實(shí)際上,這兩者...
    彥幀閱讀 3,888評論 0 14
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,058評論 25 709
  • 1.ios高性能編程 (1).內(nèi)層 最小的內(nèi)層平均值和峰值(2).耗電量 高效的算法和數(shù)據(jù)結(jié)構(gòu)(3).初始化時...
    歐辰_OSR閱讀 30,243評論 8 265
  • 我要每天都不一樣
    南弗閱讀 174評論 0 0
  • 竹山不愛吃山竹 2018-08-08 19:57 · 字?jǐn)?shù) 2112 · 閱讀 0 · 日記本 每年的夏天爸...
    竹山不愛吃山竹閱讀 427評論 0 0

友情鏈接更多精彩內(nèi)容