How to avoid infinite loop in Observer pattern?

前端 未结 5 1947
悲哀的现实
悲哀的现实 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 03:06

    If your system is single threaded, then you simply need a guard inside your notify method:

    private boolean _notifying;
    
    public void notify() {
      if(_notifying) {
        return;
      }
      _notifying = true;
      try {
        // ... do notifying here...
      } finally {
        _notifying = false;
      }
    }
    

提交回复
热议问题