在我的应用程序中,我有View
来观察Model
的变化。 Controller
负责处理 View
分派(dispatch)的事件并更新 Model
。
为了举例,假设我有两种观点。首先,InputView
包含两个 JSpinner
元素(Spinner1
和 Spinner2
)。其次,ResultView
包含带有来自微调器的值的 JLabel
。作为附加约束,我们希望 Spinner2
的值依赖于 Spinner1
的值。可以说,Spinner2
中的最小值应该是 Spinner1
当前值的 2x
。
当我们更改Spinner1
的值时,Controller
接收ChangeEvent
并更新Model
。由于我们还必须调整 Spinner2
的值,因此将调度另一个 ChangeEvent
并第二次更新 Model
。此架构的问题在于,每次 Model
更新时,观察的 View
都会刷新。因此,在此示例中,View
将刷新 3 或 4 次,而不是一次(Spinner1
更改、Spinner2
最小值更改、Spinner2
值变化)。这会导致闪烁。
如何确保在所有更改完成后 View
仅更新一次?
最佳答案
“谁触发更新?主体和它的观察者依靠通知机制保持一致。但是什么对象真正调用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.
第二个选项可能对您有用。
关于Java MVC : Updating View using Observer pattern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8777910/