我正在使用Swing GUI编写实用程序。我试图使用Martin的表示模型来方便测试。我的应用程序将使用java.util.prefs.Preferences自动存储多个用户首选项(即:主窗口位置和大小)。这个周末,我花了几个小时试图创建一个Preferences API的Clojure模拟(使用EasyMock),这样我就可以测试我的演示程序代码,但是无法让它工作。对于长期从事OO编程的程序员来说,使用非OO风格的Clojure GUI编程是很困难的。我觉得,如果我能够发现/开发这些东西的模式(模拟、可视化“类”的“接口”等等),我可以在应用程序的其余部分继续使用相同的模式。
我还一直在Scala中开发相同的应用程序来比较编程模式,并且发现它更直观,尽管我试图以相当严格的功能风格使用Scala (当然,不包括对Swing API这样的Java类的调用--它在calls版本中会有相同的可更改性问题,但当然也会是单线程的)。
在我的Scala代码中,我创建了一个名为MainFrame的类,它扩展了JFrame并实现了特征MainView。MainView将所有JFrame调用公开为我可以在模拟对象中实现的抽象方法:
trait LabelMethods {
def setText(text: String)
//...
}
trait PreferencesMethods {
def getInt(key: String, default: Int): Int
def putInt(key: String, value: Int)
//...
}
trait MainView {
val someLabel: LabelMethods
def addComponentListener(listener: ComponentListener)
def getLocation: Point
def setVisible(visible: Boolean)
// ...
}
class MainFrame extends JFrame with MainView {
val someLabel = new JLabel with LabelMethods
// ...
}
class MainPresenter(mainView: MainView) {
//...
mainView.addComponentListener(new ComponentAdaptor {
def componentMoved(ev: ComponentEvent) {
val location = mainView.getLocation
PreferencesRepository.putInt("MainWindowPositionX", location.x)
PreferencesRepository.putInt("MainWindowPositionY", location.y)
}
mainView.someLabel.setText("Hello")
mainView.setVisible(true)
}
class Main {
def main(args: Array[String]) {
val mainView = new MainFrame
new MainPresenter(mainView)
}
}
class TestMainPresenter {
@Test def testWindowPosition {
val mockPreferences = EasyMock.mock(classOf[PreferencesMethods])
//... setup preferences expectation, etc.
PreferencesRepository.setInstance(mockPreferences)
val mockView = EasyMock.createMock(classOf[MainView])
//... setup view expectations, etc.
val presenter = new MainPresenter(mockView)
//...
}
}我使用的是伪单例(包括setInstance,以便模拟可以替换“真实”版本)的首选项,因此没有显示细节。我知道蛋糕的图案,但我发现在这种情况下我的更容易使用。
我一直在为在Clojure中执行类似的代码而挣扎。有任何开源项目的好例子来做这样的事情吗?我读过几本关于Clojure的书(编程Clojure,Clojure的Joy,实用Clojure),但是我还没有看到这些问题的处理。我也研究过Rich的ants.clj,但是他在这个例子中使用Swing是非常基本的。
发布于 2020-10-21 11:17:04
请检查这两个在clojure世界中非常流行的选项:
https://stackoverflow.com/questions/5620897
复制相似问题