我有一个视图模型,该视图模型已在两个流程中使用,并且已经进入将其真正拆分为超类和两个子类的阶段。但是,对于执行某些子类化的最佳方法,我感到困惑。
在创建视图模型时,我像这样传递了视图中可能发生的所有交互:
class SomeViewController: UIViewController {
@IBOutlet private weak var nextButton: UIButton!
private var presenter: SomeViewModel!
override func viewDidLoad() {
super.viewDidLoad()
presenter.configure(nextButtonTapped: nextButton.rx.tap.asDriver())
}
}
然后,我可以在视图模型中像这样处理这些操作:
class SomeViewModel {
private let normalFlow: Bool
private let diposeBag = DisposeBag()
init(normalFlow: Bool) {
self.normalFlow = normalFlow
}
func configure(nextButtonTapped: Driver<Void>) {
handle(nextButtonTapped: nextButtonTapped)
// call to any other input handlers here...
}
func handle(nextButtonTapped: Driver<Void>) {
nextButtonTapped.drive(onNext: { [unowned self] in
guard self.safetyCheckOnePasses(), safetyCheckTwoPasses() else {
return
}
if normalFlow {
// do some set of actions
} else {
// do another set of actions
}
}).disposed(by: disposeBag)
}
func safetyCheckOnePasses() -> Bool {
// perform some sanity check...
return true
}
func safetyCheckTwoPasses() -> Bool {
// perform another sanity check...
return true
}
}
我对重写handle(nextButtonTapped: Driver<Void>)
的最佳方法感到困惑,是因为我仍然希望对每个子类在onNext
的开头进行健全性检查,但是我希望之后的主体是不同的子类也不同。无需复制代码的最佳方法是什么?
Rx是功能范式的一部分,因此,不适合使用子类。
将safetyCheckOnePasses()
和safetyCheckTwoPasses()
函数移出类(或至少使其变为静态。)这样,就可以在不需要实例的情况下重用它们。