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

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

问题描述

我只有一个班很多实例。每个实例都是其他几个实例的观察者。同样,每个实例也可以被其他几个实例观察到。

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.

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

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

推荐答案

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

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天全站免登陆