Scala model-view-presenter,特征 [英] Scala model-view-presenter, traits

查看:46
本文介绍了Scala model-view-presenter,特征的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Martin Fowler(已弃用的)model-view-presenter模式的粉丝.我正在写一个包含几个按钮类的Scala视图类.我想提供一些方法来设置按钮的动作属性,以供演示者调用.一个典型的代码片段如下所示:

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) }

每个按钮都重复此代码.如果Java/Scala具有C预处理程序,那么我将创建一个宏来生成此代码,并给出按钮名称(请不要讲授C预处理程序的弊端).该代码显然非常冗长和重复.在Scala中,有没有更好的方法(也许使用特征)?

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?

请举行有关scala.swing的讲座.我在这里寻找通用模式.

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

推荐答案

与Java相比,Scala较少涉及显式的setter和getter方法.而是使用抽象字段来定义公开的接口.这样的事情怎么样:

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
}

针对Container的类只能在内部方法将其视为JButton的情况下访问setAction.

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

另一个注意事项:C使用宏来减少代码重复. Scala使用特征的多重继承来完成同一件事.

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

这篇关于Scala model-view-presenter,特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆