Java MVC:使用Observer模式更新视图

时间:2012-01-08 13:26:26

标签: java model-view-controller swing

在我的应用程序中,我View观察到Model更改。 Controller负责处理View发送的事件并更新Model

为了举例,假设我有两个视图。首先,InputView包含两个JSpinner元素(Spinner1Spinner2)。其次,ResultView包含来自微调器的值的JLabel。作为附加约束,我们希望Spinner2的值取决于Spinner1的值。可以说,Spinner2中的最小值应为2x当前值Spinner1

当我们更改Spinner1 Controller收到ChangeEvent的值并更新Model时。由于我们还必须调整Spinner2的值,因此将调度另一个ChangeEvent,并且Model将在第二次更新。此架构的问题在于,每次Model更新时,观察View都会刷新。因此,在此示例中,View将刷新3或4次而不是一次(Spinner1更改,Spinner2最小值更改,Spinner2值更改)。这会导致闪烁。

如何在完成所有更改后确保View只更新一次?

3 个答案:

答案 0 :(得分:2)

gang-of-four book说:

“谁触发更新?主题及其观察者依赖通知机制保持一致。但是实际上调用Notify触发更新的对象是什么?这里有两个选项:

Have state-setting operations on Subject call Notify after they change the 
subject's state. The advantage of this approach is that clients don't have 
to remember to call Notify on the subject. The disadvantage is that several
consecutive operations will cause several consecutive updates, which may be
inefficient.

Make clients responsible for calling Notify at the right time. The advantage 
here is that the client can wait to trigger the update until after a series 
of state changes has been made, thereby avoiding needless intermediate updates.
The disadvantage is that clients have an added responsibility to trigger the 
update. That makes errors more likely, since clients might forget to call Notify.

第二个选项可能对您有用。

答案 1 :(得分:1)

文章Java SE Application Design With MVC: Issues With Application Design将问题置于上下文中,并建议使用属性更改“检查模型的传入更改值与存储在Swing组件中的当前值。”

答案 2 :(得分:1)

这就是观察的完成方式:

label -> spinner 2 -> spinner 1

如果我是你,我会设置“改变类型”。因此,在我的控制器中,我可以控制如何通知我的观察者。

如果您发布代码,我会更有帮助。