Implementation patterns to avoid infinite loops with events
A naive implementation of MVC leeds to infinite loops.
Example: Model is a Workbook with Worksheets, View is a Tabbar with Tabs
- User interakts with Tabbar to create new Tab
- Tabbar sends event onTabAdded to Controler
- Controler calls Workbook.addWorksheet()
- Workbook sends event onWorksheetAdded to Tabbar
- Tabbar adds Tab and sends onTabAdded to Controler -> 2) Infinite Loop!
Alternatively, the loop could be initiated by programmatically adding a Worksheet through a macro. Or a tab could be added programmatically by automated UI testing.
It seems that the more components you have and the looser the coupling is (considered good design), the more likely it is to have infinite loops.
开发者_JAVA技巧Do you know about implementation patterns how to avoid such infinite loops? An evaluation of pros/cons of such patterns?
My special interest is a solution for a rich JavaScript client.
The answers to the following questions are not really on the implementation level:
- should the Observer Pattern include some infinite loop detection?
- Event driven architecture...infinite loop
- how to avoid infinite loop in observer pattern?
You would typically code something like this (pseudo code):
boolean inEventProcessing = false;
processEvent(event){
if inEventProcessing return
inEventProcessing = true
doProcessEvent(event)
inEventProcessing = false
}
The alternative is to make sure that by construction no loops happen. This is the conceptual cleaner way, but hard to do if you don't come up with it in the very beginning. One way would be to allow Observers only arguments to the constructors of Observables. This way it would be impossible to construct loops. But it is a extremely rigid structure which probably causes all kinds of different problems.
I do suspect the solution of those problems would lead to a really nice and clean architecture or to a complete and extreme mess, depending on the team working with it.
精彩评论