Scala model-view-presenter, traits

情到浓时终转凉″ 提交于 2020-01-11 12:12:46

问题


I am a fan of Martin Fowler's (deprecated) model-view-presenter pattern. I am writing a Scala view class containing several button classes. I would like to include methods to set the action properties of the buttons, to be called by the presenter. A typical code fragment looks like this:

private val aButton = new JButton
def setAButtonAction(action: Action): Unit = { aButton.setAction(action) }

This code is repeated for each button. If Java/Scala had the C preprocessor, I would create a macro to generate this code, given the button name (no lectures on the evils of the C preprocessor, please). This code is obviously very verbose and repetitive. Is there any better way way to do this in Scala, perhaps using traits?

Please hold the lectures about scala.swing. I looking for a general pattern here.


回答1:


Scala is less about explicit setter and getter methods than java. Instead use abstract fields to define the exposed interface. How about something like this:

trait ActionUser {
  def setAction(action:Action):Unit
}

trait Container {
  val aButton:ActionUser
}

trait ContainerImpl {
  val aButton = new JButton with ActionUser
}

Classes operating against Container will only be able to access setAction while internal methods see it as a JButton.

One more note: C uses macros to cut down on code duplication. Scala uses multi-inheritance of traits to accomplish the same thing.



来源:https://stackoverflow.com/questions/2915041/scala-model-view-presenter-traits

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!