2012-01-08 107 views
0

在我的应用程序中,我有View观察到Model更改。 Controller负责处理由View派遣的事件和更新ModelJava MVC:使用观察者模式更新视图

为了举例,假设我有两个视图。首先,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只更新一次?

+0

请张贴SSCCE,因为我不知道闪烁,您的代码中必须存在另一个棘手的问题 – mKorbel 2012-01-08 13:56:55

+0

闪烁我的意思是随之而来的刷新视图。如果我们使用某种图表或任何比标签更复杂的图表,多个刷新将会显示 – 2012-01-08 16:00:41

回答

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

因此,这是怎么观察做:

label -> spinner 2 -> spinner 1 

如果我是你,我会成立‘类型更改’。所以在我的控制器中,我可以控制如何通知我的观察员。

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

+0

不,标签会观察模型。带旋钮的面板也观察'模型'。每个'spinner'都将'state changes'分配给'Controller',它修改'Model'。此时,'InputView'更新从属'spinner 2'的值,该值激发了Model的第二次更新 – 2012-01-08 16:03:50