代理與單例是 iOS 開發中最基礎、最常用的兩種設計模式。下面用 Swift 演示它們的典型寫法。
先定義一個代理協議,聲明需要回調的方法;再由持有者通過 weak 引用調用代理方法,避免循環引用。
protocol FallingObjectDatasourceDelegate:class{ func didCollisionWithTheBallBundary(sender:FallingObjectDatasource , numberOfDisappearedBalls:Int) func didCollisionWithTheBottomBundary(sender:FallingObjectDatasource) } class FallingObjectDatasource: NSObject{ //申明delegate public weak var delegate:FallingObjectDatasourceDelegate? func collisionBehavior(_ behavior: UICollisionBehavior, endedContactFor item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?){ if(identifier != nil) , identifier as! String == PathNames.ballBundaryName{ self.delegate?.didCollisionWithTheBallBundary(sender: self, numberOfDisappearedBalls: self.totalDrops - self.drops.count) }else if identifier as? String == PathNames.referenceBundayName{ self.delegate?.didCollisionWithTheBottomBundary(sender: self) } } }
接下來,只需在需要使用代理的類中實現協議方法即可。
利用 Swift 的私有全局常量配合 dispatch_once 語義,可以實現線程安全的單例:
private let shareInstance = GameEngine() class GameEngine: NSObject,FallingObjectDatasourceDelegate { class var share: GameEngine { return shareInstance } }
使用時直接調用 GameEngine.share.方法名 即可。這種寫法簡潔直觀,也是 Swift 中實現單例的推薦做法。