Swift,iOS:如何从混凝土类型中获得多态性和脱致协调员
我有以下协议:
protocol Coordinator {
var rootViewController: UIViewController { get set }
func start()
}
protocol UIViewControllerFactory {
func mainViewController() -> UIViewController
}
我创建了一个符合此协议的Main Coordinator ,并且通过了一个工厂,该工厂使我可以将协调器解脱出来,无法创建和捕获混凝土类型,因此可以是 polymormormorphic < /strong>,可以与 uiviewController的更多实现一起使用, rootviewControllers 和 mainmenuviewController ,如下所示:
class MainCoordinator: Coordinator {
var rootViewController: UIViewController
let factory: UIViewControllerFactory
init(rootViewController: UIViewController, factory: UIViewControllerFactory) {
self.rootViewController = rootViewController
}
start() {
guard let mainVC = factory.mainViewController() as? MainViewController, let rootViewController = rootViewController as? UINavigationViewController else { return }
mainVC.delegate = self
rootViewController.push(mainVC, animated: true)
}
尽管我可以看到,但VE创建了协调器,以接受UiviewController的任何子类,它已在 start 函数中耦合到UiviewController的具体实现:MainViewController。
我如何将其从mainviewController中解脱出来,并使它更多态?
I have these protocols:
protocol Coordinator {
var rootViewController: UIViewController { get set }
func start()
}
protocol UIViewControllerFactory {
func mainViewController() -> UIViewController
}
And I created a MainCoordinator that conforms to this protocol and I pass a factory that allows me to decouple the coordinator from creating and capturing a concrete type so it can be polymorphic and can be used with more implementations of UIViewController either as rootViewControllers and mainMenuViewController as shown below:
class MainCoordinator: Coordinator {
var rootViewController: UIViewController
let factory: UIViewControllerFactory
init(rootViewController: UIViewController, factory: UIViewControllerFactory) {
self.rootViewController = rootViewController
}
start() {
guard let mainVC = factory.mainViewController() as? MainViewController, let rootViewController = rootViewController as? UINavigationViewController else { return }
mainVC.delegate = self
rootViewController.push(mainVC, animated: true)
}
As you can see, although I've created the coordinator to accept any subclass of UIViewController it has been coupled in the start function to the concrete implementation of UIViewController: MainViewController.
How can I decouple it from MainViewController and have it more polymorphic?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将协调器作为出厂函数中的参数类型传递,并在创建Controller实例时直接在出厂功能中进行
委托
。这样,您就不必将Controllertype
显式地从工厂类中出现。我想到了以下方法。
You can pass coordinator as a parameter type in factory function and set
delegate
directly in factory function while creating controller instance. That way you wouldn’t have to expose controllertype
explicitly out of factory classes.I came up with below approach.