TornadoFX - 创建MVP设计

时间:2016-08-11 22:04:31

标签: javafx kotlin mvp tornadofx

您好我是否使用TornadoFX,我想知道MVP结构的最佳设计是使用TornadoFX?

在MVP视图中:

- >会将所有事件(例如按钮点击)委托给演示者

中的某个功能

- >不与模型互动

以下是一些粗略的原型想法:

abstract class AbstractPresenter<View : tornadofx.View> : Controller() {

var view: View by Delegates.notNull()

fun attachView(view: View) {
    this.view = view;
 }
}

我创建了一个将自身附加到AbstractView的演示者:

abstract class AbstractView<out Presenter : AbstractPresenter<*>> : View() {

abstract val presenter: Presenter

}

现在在示例中使用它:

class SampleTestView: AbstractView<SampleTestPresenter>() {

override val presenter: SampleTestPresenter by inject()
override val root: AnchorPane by fxml()

val testButton: Button by fxid()

init {
    presenter.attachView(this)
    testButton.setOnAction { presenter.doSomething() }
   }

}

Sample Presenter:

class SampleTestPresenter: AbstractPresenter<SampleWindowView>() {

fun doSomething() {
    println("did it")
}

}

使用TornadoFX这是一个不错的MVP模式实现吗?

修改

做了一些改变:

class SampleWindowView : View() {
override val root: AnchorPane by fxml()
val presenter : SampleWindowViewPresenter by inject()

val button:Button by fxid()

init {
    button.setOnAction {  presenter.handleButtonClick() }
  }
}


class SampleWindowViewPresenter : Controller() {

val sampleView: SampleWindowView by inject()

fun handleButtonClick() {
    println("clicked")
  }
}

1 个答案:

答案 0 :(得分:1)

总结上面的讨论,你可以做到:

class SampleTestView : View() {
    val presenter: SampleTestPresenter by inject()

    override val root: AnchorPane by fxml()
    val testButton: Button by fxid()

    init {
        testButton.setOnAction { presenter.doSomething() }
    }
}

class SampleTestPresenter : Controller() {
    val view: SampleTestView by inject()

    fun doSomething() {
        println("Did the thing")
    }
}

如果您想确保视图有一个演示者,您可以创建一个抽象视图并从中扩展所有视图:

abstract class AbstractView<Presenter : Controller> : View() {
    abstract val presenter: Presenter
}