2012-01-08 26 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