在我的应用程序中,我View
观察到Model
更改。 Controller
负责处理View
发送的事件并更新Model
。
为了举例,假设我有两个视图。首先,InputView
包含两个JSpinner
元素(Spinner1
和Spinner2
)。其次,ResultView
包含来自微调器的值的JLabel
。作为附加约束,我们希望Spinner2
的值取决于Spinner1
的值。可以说,Spinner2
中的最小值应为2x
当前值Spinner1
。
当我们更改Spinner1
Controller
收到ChangeEvent
的值并更新Model
时。由于我们还必须调整Spinner2
的值,因此将调度另一个ChangeEvent
,并且Model
将在第二次更新。此架构的问题在于,每次Model
更新时,观察View
都会刷新。因此,在此示例中,View
将刷新3或4次而不是一次(Spinner1
更改,Spinner2
最小值更改,Spinner2
值更改)。这会导致闪烁。
如何在完成所有更改后确保View
只更新一次?
答案 0 :(得分:2)
“谁触发更新?主题及其观察者依赖通知机制保持一致。但是实际上调用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
如果我是你,我会设置“改变类型”。因此,在我的控制器中,我可以控制如何通知我的观察者。
如果您发布代码,我会更有帮助。