Locatable
上下文
Locatable 是一个 Swift 微框架,通过自定义属性 @Locatable
使用属性包装器来实施服务定位模式。
以下是一个使用示例
protocol Servicing {
func action()
}
class Service: Servicing {
func action() {
print("I'm performing a service 😊")
}
}
Locator.register(Servicing.self, { return Service() })
class MyController {
@Locatable(.sharedInstance) var service: Servicing
func work() {
self.service.action()
}
}
let controller = MyController()
controller.work() // I'm performing a service 😊
为了方便,还提供了一些缩写语法
// leverages @autoclosure
Locator.register(Servicing.self, Service())
// leverages default argument values
Locator.register { return Service() as Servicing }
服务定位支持两种不同的语义
// Will return an instance that is shared across the app
Locatable(.sharedInstance) var service: Servicing
// Will return a new instance every time
Locatable(.newInstance) var service: Servicing
需求
Xcode 11+ & Swift 5.1
安装
CocoaPods
将以下内容添加到您的 Podfile
中
pod "Locatable"
Carthage
将以下内容添加到您的 Cartfile
github "vincent-pradeilles/locatable"