[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の場合:
以前に作成したコンテンツ
見ても読めないので、見たリンクを整理しておきましょう…
Reference
この問題について([swift] Deligate Pattern), 我々は、より多くの情報をここで見つけました https://velog.io/@gosari/swift-Deligate-Patternテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol