设计模式之 delegate 委托模式:Swift 实现

本文介绍了iOS开发中的委托模式(DelegateMode),通过Game和GameDelegation协议展示了如何将复杂操作从Game类中移交给专门的委托对象SnakeTracker执行。讨论了委托模式与代理模式的区别,并在实际代码示例中阐述了委托模式的运用,例如在UITableView中的应用。此外,还提及了在iOS UIKit中遵循协议以实现委托功能的常见做法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Delegate Mode 委托模式:

类 A 中实现具体功能的方法移动到 B 中,B 为受委托对象,B 中的方法都是需要输入一个 A 的引用,从而才能让 B 替 A 做一些具体且复杂的操作。相当于 A 把复杂的操作委派给 B 来完成。

委托模式
game 拥有一个 GameDelegation . 接着输入 Game 实例到 Delegation 的实例,这个委派者可以做一些本来应该由 Game 的实例来完成的细节的事情。这样的模式称为委派模式。

委托模式与代理模式区别在于,代理模式更为严格,代理者和被代理者都共同遵守同一“已声明方法”的顶层协议;而委托模式则不需要。

// Delegation
protocol Delegation {
    func gameDidStart(_ game: Game)
    func game(_ game: Game)
    func gameDidEnd(_ game: Game)
}

// Game
protocol Game {
    var delegation: Delegation? { get set }
    func play()
}
// Concrete Deleagtion
class SnakeTracker: Delegation {
    func gameDidStart(_ game: Game) {
    }
    
    func game(_ game: Game) {
        // do something
    }
    func gameDidEnd(_ game: Game) {
    }
}

// Concrete Game
class SnakeGame: Game {
    var delegation: Delegation?
    init(_ delegation: Delegation) {
        self.delegation = delegation
    }
    func play() {
        delegation!.gameDidStart(self)
        delegation!.game(self)
        delegation!.gameDidEnd(self)
    }
}
let gameTracker = SnakeTracker()
let game = SnakeGame(gameTracker)
game.play()  // It's the func of the game, but the detail work is done by the delegation.

iOS 的 UIKit 中代理模式很常见,比如要使用 UITableView,那么让当前的 controller 遵守 UITableViewDatasource 协议和 UITableViewDelegate 协议,即可让当前的 controller 作为一个代理者的身份来设定对应方法的要如何执行设定如何响应来自界面的操作等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值