如何避免观察者模式的无限循环? [英] how to avoid infinite loop in observer pattern?

查看:583
本文介绍了如何避免观察者模式的无限循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只有一个类有很多实例。每个实例都是其他几个实例的观察者。每个实例都可以通过另外一个实例来观察。



如何避免在观察者中调用update()的无限循环?

解决方案

您正在寻找的是一种检测周期的图遍历算法。一种简单的方法(仅在单个线程的情况下工作)是保留一个全局/静态计数器,以使每个顶级 update()调用获得唯一的标识符。然后,每个观察者跟踪是否已经使用给定的标识符(ID)处理了更新,并且在这种情况下忽略它。这意味着您的更新方法必须使用具有特定更新ID号的参数进行扩展。


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.

How to avoid infinite loop of calling update() in observers?

解决方案

What you are looking for is a graph-traversal algorithm that detects cycles. One simple approach (that only works in a single threaded scenario) is to keep a global/static counter to let each top-level update() invocation get a unique identifier. Each observer then tracks whether already it has processed the update with the given identifier (ID) and in that case ignores it. This means that your update method will have to be expanded with a parameter with the ID number of the specific update.

这篇关于如何避免观察者模式的无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆