观察者设计模式及其他

发布于 2024-09-07 09:32:04 字数 270 浏览 1 评论 0原文

我开始阅读设计模式并尝试将它们应用到某些编码中。我读过有关观察者模式的内容,并认为它将是最有用的一种。

我的两个问题是: 1)如果我希望我的对象既是观察者又是主体,是否只是让它同时继承观察者和主体类的问题?假设我的军队中有多个单位,我希望他们能够快速相互发送本地更新。它是否像我所描述的那样工作,或者是否完全需要另一种模式?

2)如果一个对象需要与许多不同性质的类型进行通信(比如将军需要与他的单位、派系领导人等进行通信),观察者模式仍然有效吗?我想这只是一个实施问题,但我不知道......

I'm starting to read about design patterns and trying to apply them to some coding. I've read about the observer pattern and think it would be a most useful one to make use of.

My two questions are these:
1) If I want my object to be both an observer and a subject, is it simply a question of making it inherit from both the observer and the subject class? Say I have several units in an army, and I want them to quickly send local updates to each other. Does it work as I have described, or does it necessitate another pattern completely?

2) If an object needs to communicate with types of many a different nature (say a general needs to communicate with his units, with the faction leader, etc.), does the observer pattern still work? I guess it would just be a question of implementation, but I don't know...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

水染的天色ゝ 2024-09-14 09:32:04

通常,观察者模式是应用分层方法:较高级别的对象控制较低级别的对象,并且它是观察者,因此它可以对较低级别对象的状态更改做出反应。
在您的情况下,您希望在对等体之间进行通信,并且希望所有对象彼此了解,因此观察者不会增加真正的价值。
如果在单元之上有一个知道如何更新更新的控制对象,那么观察者会工作得更好。

当然,这取决于您来决定这是否更适合您的情况。

顺便说一句,检查 Boost 信号 作为您的实现观察者

Normally, the observer patterns is about applying a layered approach: a higher level object controls a lower level one and it is an observer, so it can react on changed status of the lower level object.
In your case, you want communication between peers and you want all objects to know each other, so observer doesn't add real value.
Observer would work better if there would be a controlling object on top of the units that knows what to do on updates.

Of course, it is up to you to decide wheter this would work better in your case.

BTW, check boost signals as an implementation for your observer

浮世清欢 2024-09-14 09:32:04

1) 如果我希望我的对象既是
观察者和主体,难道只是一个
让它继承的问题
既是观察者又是主体
类?

是的。

2) 如果对象需要通信
具有许多不同性质的类型
观察者模式还有效吗?

是的。

以防万一您切换到 .NET/C#,有一个很好的库用于响应/处理来自可观察对象的事件:Rx http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx

1) If I want my object to be both an
observer and a subject, is it simply a
question of making it inherit from
both the observer and the subject
class?

Yup.

2) If an object needs to communicate
with types of many a different nature
does the observer pattern still work?

Yup.

Just in case you switch to .NET/C# there's a nice library for reacting to/processing events from observables: Rx http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文