观察者设计模式及其他
我开始阅读设计模式并尝试将它们应用到某些编码中。我读过有关观察者模式的内容,并认为它将是最有用的一种。
我的两个问题是: 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常,观察者模式是应用分层方法:较高级别的对象控制较低级别的对象,并且它是观察者,因此它可以对较低级别对象的状态更改做出反应。
在您的情况下,您希望在对等体之间进行通信,并且希望所有对象彼此了解,因此观察者不会增加真正的价值。
如果在单元之上有一个知道如何更新更新的控制对象,那么观察者会工作得更好。
当然,这取决于您来决定这是否更适合您的情况。
顺便说一句,检查 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
是的。
是的。
以防万一您切换到 .NET/C#,有一个很好的库用于响应/处理来自可观察对象的事件:Rx http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx。
Yup.
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.