How to avoid infinite loop in Observer pattern?

前端 未结 5 1976
悲哀的现实
悲哀的现实 2021-01-03 02:35

I have only one class with many instances. Every instance is observer of couple of other instances. As well every instance can be observable by couple of another instances.<

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-03 02:57

    Well, if you are defining the "event" object, you could maybe add to it the objects that have processed the event already. In that case, if you close the loop you can exit. In seudo-code

    eventFired(Event e)
      if (e.hasBeenEvaluatedBy(this)){
        return;
      }
      e.addEvaluator(this);
    
      // Do magic
    
      refire(e);
    }
    

    In this case we get something like: * A fires something. * B processes it and adds itself to the list * B refires * C processes event and adds itself to the list * C refires * A processes the event and adds itself to the list * A refires * B catches the event, but is already on the list. No refire, infinite loop broken

    Ids could be used instead of pointers to avoid garbage collection issues

提交回复
热议问题