[swift] Deligate Pattern

15856 ワード

ケース1

// MARK: -Delegation 없이 두 객체가 서로를 보는 경우

class Writer {
    var writtenScriptPage: Int
    var manager: Manager?
    var gameID: String
    var hasFinalScript: Bool

    init(writtenScriptPage: Int, manager: Manager, gameID: String, var hasFinalScript: Bool = false) {
        self.writtenScriptPage = writtenScriptPage
        self.manager = manager
        self.gameID = gameID
        self.hasFinalScript = hasFinalScript

        self.manager?.writer = self
    }

    func write(for hours: Int) {
        self.writtenScriptPage += hours
    }

    func proofread() {
        hasFinalScript = true
    }
}

class Manager {
    var writer: Writer?

    init() {
        self.writer?.manager = self
    }

    func upload() {
        writer?.proofread()

        let finalScript = writer?.hasFinalScript
        if finalScript != nil {
            print("최종본이 업로드되었습니다.")
        } else {
            print("작가가 기한 내 원고를 제출하지 못했습니다.")
        }
    }
}

let manager = Manager()
let writer = Writer(writtenScriptPage: 350, manager: manager, gameID: "gosari9876")

manager.upload()

ケース2

// MARK: - Delegation을 이용하는 경우

protocol Writable {
    var manager: Manageable? { get set }
    var hasFinalScript: Bool { get }
    
    func proofread()
}

protocol Manageable {
    var writer: Writable? { get set }
}

class Writer: Writable {
    var writtenScriptPage: Int
    var manager: Manageable?
    var gameID: String
    var hasFinalScript: Bool
    
    init(writtenScriptPage: Int, manager: Manageable?, gameID: String, var hasFinalScript: Bool = false) {
        self.writtenScriptPage = writtenScriptPage
        self.manager = manager
        self.gameID = gameID
        self.hasFinalScript = hasFinalScript
        
        self.manager?.writer = self
    }
    
    func write(for hours: Int) {
        self.writtenScriptPage += hours
    }
    
    func proofread() {
        hasFinalScript = true
    }
}

class Manager: Manageable {
    var writer: Writable?
    
    init() {
        self.writer?.manager = self
    }
    
    func upload() {
        writer?.proofread()
        
        let finalScript = writer?.hasFinalScript
        if finalScript != nil {
            print("최종본이 업로드되었습니다.")
        } else {
            print("작가가 기한 내 원고를 제출하지 못했습니다.")
        }
    }
}

let manager = Manager()
let writer = Writer(writtenScriptPage: 350, manager: manager, gameID: "gosari9876")

manager.upload()

ケース1の場合:

  • 参照ループが発生します.
  • 各オブジェクトの責任ではなく、他のオブジェクトの情報にアクセスできます.

    ケース2の場合:

  • ケース1の問題が追加されます.
  • SOLIDのオープン‐クローズドの原則に従う.
  • 以前に作成したコンテンツ


    見ても読めないので、見たリンクを整理しておきましょう…
  • 正式文書-契約/説明
  • iOS Delegateモードについて
  • Delegation in Swift Explained
  • swift delegation swiftインクリメンタルゲートの概念を理解する
  • [Swift]取引モード