Context, an iOS app using UIKit and MVC.
Model A has a singleton object, and one of its property value (foo
in this case) can be changed during the runtime. Model B has a property, Model C, that is initialized using the property value of Model A.
class ModelA {
private(set) var foo: CustomObjectClassName
static let shared = ModelA()
}
class ModelB {
private var bar: ModelC
init() {
self.bar = ModelC(ModelA.shared.foo)
}
// TODO: Observer `foo` value change in Model A and then
// reinit ModelC to replace the old `bar` object
}
What is the common design pattern or mechanism that should be used to let Model B know about property change in Model A and re-initialize its own property?
I found two patterns that can be used; however, the more I read about them, they seem to be designed for communication between Model and Controller.
Related Information
Using Key-Value Observing in Swift, https://developer.apple.com/documentation/swift/cocoa_design_patterns/using_key-value_observing_in_swift
NotificationCenter, https://developer.apple.com/documentation/foundation/notificationcenter
Thanks for El Tomato comment, delegation can be a pattern be used.
A delegation pattern would work since in my case Model A is only used by a single entity Model B.
protocol ModelADelegate {
func fooDidChange() -> Void
}
class ModelA {
public var delegate: ModelADelegate?
private(set) var foo: CustomObjectClassName {
didSet {
delegate.fooDidChange()
}
}
static let shared = ModelA()
}
class ModelB, ModelADelegate {
private var bar: ModelC
init() {
ModelA.shared.delegate = self
self.bar = ModelC(ModelA.shared.foo)
}
func fooDidChange() {
self.bar = ModelC(ModelA.shared.foo)
}
}