How to avoid infinite loop in Observer pattern?

前端 未结 5 1949
悲哀的现实
悲哀的现实 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:54

    Let your observers add received events (or their ids) to some temporary storage and when every new event is received let them verify whether the same event is saved in the storage. If it is then they shouldn't handle it.

    But if we'll try to solve a problem rather than find a suitable workaround then: your problem is that object A can listen to object B, and object B can listen to object A at the same time (maybe with some intermediary objects). It's a bad design IMHO.

    Observers should be used to loose coupling, making object A know about object B, but not vice versa.

    If your objects A and B both know about each other then I don't see why you need to use observers.

提交回复
热议问题