|
|
Comments and Discussions
|
|
 |

|
I think it only makes sense to list if you won a monthly competition, if that. Listing your place seems excessive.
|
|
|
|

|
when we look at observer pattern diagram, seems it impose to implement the subject and object methods in concrete subject & concrete object. but you implemented in subject & object itself. but at the same time, it is ok since it also fulfills the single responsibility principle. I am not sure, but Just confused, any one can clarify it?
Thanks
|
|
|
|

|
Really very useful to understand Observer.
|
|
|
|

|
Clear, concise, and the code works
|
|
|
|

|
As usual you are just regurgitating things and providing little (if any) context to assist anyone who is actually LEARNING, and the examples provided are very thin if used as a reference for someone who already understands the pattern and wants to see a C implementation.
modified 26-Mar-12 19:30pm.
|
|
|
|

|
This article should not be in this section. There is not C in the article itself and only a very limited obviously layman's attempt at a C implementation. This should be moved to the C# section.
|
|
|
|

|
The usefulness of the base classes can be improved by templating them. This would allow the Notify and Update fuctions to be able to send data based on a type dictated by the template parameter, rather than being fixed.
template <typename TUpdate>
class IObserver
{
public:
virtual void Update(TUpdate value) = 0;
};
|
|
|
|

|
14th February: Edit to remove misunderstanding
Nice short and to the point. I gave it a four as it showed very clear how an Observer implementation could work.
1) Have you given any thoughts to push vs pull of the data after/with the notification?
2) the Observer pattern is a great teaching example.. However., What if classes need to publish/subscribe to/from several other entities and data? It is easy to see how the code can deteriorate with just a few multiple inheritances.
I.m.h.o a much improved technique is "signals and slots". It is really just a generation improvement of the Observer pattern but relying on composition instead of inheritance which greatly helps in keeping the design "clean". It takes the loosely coupled Observer pattern one step further and solves exactly the same problem but without inheritance. In case of Huge amounts of data this is also more efficient since virtual calls can be avoided.
There exist a multitude of "signal-and-slots" implementations from the original Qt's (the only threadsafe signal communication) using "mock" to more advanced like boost::signals or even for embedded software like my own (simple yet efficient) ksignals (http://sites.google.com/site/kjellhedstrom2/signalandslots)
Check out signals-and-slots. I think you will like it.
Thanks again for the article. I am looking forward to your next
modified 14-Feb-12 9:00am.
|
|
|
|

|
KjellKod.cc wrote: 2) In my opinion the Observer pattern is a great teaching example that often (not always) is best to stay as just that, an example.
I've found the observer pattern to be very useful in embedded programming, where other architectures for communicating events (such as broadcasting) failed the real-time requirements: in various parts of our applications it was crucial that certain actuators (such as stepper motors) were stopped (or started) immediately when a certain sensor reported a change, and having every subsystem check every signal was simply too slow for our purposes.
I don't know enough about signals and slots implementations to judge whether that would have worked as well (or better), but I do know that the observer pattern worked perfectly for our requirements back then.
|
|
|
|

|
Hi Stefan and thank you for your reply.
I had to modify my initial comment as I realized that it came off as a "against Observer pattern" comment. Observer pattern is a beautiful way to make a loosely coupled system and I absolutely do not want to shoot that down.
What I wanted to say is that signals and slots come with all the advantages of Observer pattern but less of its disadvantages. If Observer pattern is great, then signal-and-slots is great++
Let me give you an example:
For reasons similar to your own we used the Observer pattern in an embedded realtime system [uVelocity on a 300Mhz Power-PC]. It was decided that the Observer type we would use would have one type of message per "inheritance" it is possible (in many ways) to have it serve different types of messages through one IObserver relationship but this will make the design less clear.
As the scope and requirements changed we had to use many more Observers, per recipient than the idea was from the beginning. Multiple inheritance is to be avoided for many reasons and we probably encountered them all ...
We then did a make over and exchanged this communication scheme for a templated signals-and-slots mechanism.
Result: Less overhead (faster), clearer design, no more inheritance needed to connect sender to recipient(s).
Observer pattern is great, but if there exist a way of giving the same functionality but without inheritance, by composition, then maybe it is worthwhile checking out?
|
|
|
|

|
I've looked over signals and slots, and found them to be not that different from the observer pattern. The main difference seems to be that it separates the logic (i. e. who signals what to whom) is separated from the observers.
I can see why that would make sense in some systems, but from an OO point of view, most objects that I can think of in the role of an observer 'know' very well what signals they should listen for, and therefore don't need that kind of separation. You may argue that an observer may not know what types of signals there may be out there, and therefore they may not know all the signals they should react to - but if that is the case, then how should the observer know how to react to that signal it doesn't know of? What's more, whether or not an observer wishes to be notified of a certain event may depend on its current state that an external object may not be aware of!
My opinion is that if there is a signal that an observer should react to, then it must 'know' of it it in the sense that it knows its interface (or an interface the observer can use to interact with it), and use that interface to register its wish to be notified.
Why must there be a separate object hat is responsible for registering the observer? And: is it even sensible to have such an object? In the system I mentioned in my previous post we've found that we had to strictly limit the notifications to the absolute minimum, just to be able to satisfy the hard real time conditions! We simply couldn't afford to wake up every observer every time a signal that might interest them popped up. Instead, we needed the observers to be able to switch off notifications during phases where they didn't matter - and only the observers themselves knew when that would be.
When I think about it, the way we implemented the observer pattern left it to each subsystem to decide for themselves whether it was the observer who did the registration or an external object. In fact, we could have one independent class for each association of a signal to an observer. However, we found that in all but a few cases it simply didn't make sense: most of the observers had to be able to switch notifications on and off at all times, just so they wouldn't get swamped by them. Anything short of that would have led to violations of hard real time conditions.
I don't argue the flexibility of signals and slots, but my experience shows that you trade a significant amount of performance for this flexibility. Depending on the system you implement, wou will have to decide which is your priority.
|
|
|
|

|
Interesting discussion Stefan. I hope we're not hijacking this article.
Please do not take my response below as being a Taliban on the subject
Personally I think it is fun to meet developers who also seem to enjoy the intricacies of OO so I just have to respond. Or maybe I am just starved for a good OO talk
Stefan_Lang wrote: I've looked over signals and slots, and found them to be not that different from the observer pattern. The main difference seems to be that it separates the logic (i. e. who signals what to whom) is separated from the observers Yes and No. Yes it is separated by removing inheritance. No "who signals what to whom" is exactly the same as for Observer pattern. Meaning this is not clear in the Observer pattern either,. at least not if a clear interface structure is being used.
But really this is semantics. Personally I think it is a great plus to completely and utterly separate the sender from the recipient and to me this is irrelevant whether done using the Observer pattern or signals-n-slots. It is just good practice to keep your software loosely coupled.
Stefan_Lang wrote: Why must there be a separate object hat is responsible for registering the observer? Using an intermediary (As in Rahuls example above) for disconnect/connect CAN be done, OR it can be done by the sender/receiver themselves as you suggest. There is nothing to stop you from using signals-n-slots and using a connect/disconnect though an interface is there?
Stefan_Lang wrote: [...] most of the observers had to be able to switch notifications on and off at all times, just so they wouldn't get swamped by them. Anything short of that would have led to violations of hard real time conditions Nothing says you cannot do this using signals-n-slots either.
[Going philosophical]
OO design need both composition and inheritance. However it is a goal in itself to keep down the amount of inheritance if you can. Long inheritance chains, multiple inheritances etc will befuddle your code. Even the creators of "Design Patterns: Elements of Reusable Object Oriented Software" stated that
"Favoring object composition over class inheritance helps you keep each class encapsulated and focused on one task. Your classes and class hierarchies will remain small and will be less likely to grow into unmanageable monsters.."
Signals-n-Slots will remove an inheritance level that is simple no longer needed. It will do that while still having all the good traits of the Observer pattern.
[Real-Time Performance]
On an x86/x64 system virtual calls is no big deal. In fact the virtual call overhead is probably almost as fast as a normal function call.. On a RISC platform such as for the Power PC (like for the project I mentioned earlier) then the overhead for virtual calls compared to a straight function call can be significant.
If you then are unlucky enough to have an "Observer" that needs to receive several types of data and use multiple-inheritance to get it then you are on a downhill slope. Using signals-n-slots can mean (depending on signal implementation of course) that sending of data is not done through virtual calls. This can be of extra importance, especially for RISC architecture in real-time systems.
Stefan_Lang wrote: I don't argue the flexibility of signals and slots, but my experience shows that you trade a significant amount of performance for this flexibility. Depending on the system you implement, wou will have to decide which is your priority.
Ah. To be nitpicking: You had no prior experience of signals-n-slots so this is solely from your Observer pattern experience, right?
I hope my reply above have shown you that this does not have to be the case. That in fact you can keep the flexibility, or not, using signal-n-slots while getting improved performance as well.
|
|
|
|

|
KjellKod.cc wrote: Meaning this is not clear in the Observer pattern either,. at least not if a clear interface structure is being used.
Ah, you've got me there. In fact, we did use separate objects at first to implement the callback interface that was to notify the observers. That way we didn't have to use multiple inheritance for the observers. However, we later realized that there really was no point in creating individual objects for each and every connection. And also, when it became apparent we couldn't afford to keep all connections active all of the time, the logical step was to move that logic into the observers.
KjellKod.cc wrote: There is nothing to stop you from using signals-n-slots and using a connect/disconnect though an interface is there?
Yes, in fact there is: As I pointed out, the connection in that case I mentioned often depended on the observers inner state. That means any external object activating or deactivating that connection would have had to be notified of a change of that state, turning it into an observer! It would be rather ironic to decouple an observer from its duty to maintain its connections by introducing an observer to that observer!
KjellKod.cc wrote: Nothing says you cannot do this using signals-n-slots either.
Well, yes, of course. If we had known about that 10 years ago we might have considered it. That doesn't mean we would have used it.
KjellKod.cc wrote: OO design need both composition and inheritance.
Yes, and that is my whole point. There are times when you need inheritance, and others where you need composition. Going purely by OO principles, you should make your design based on the relationship of the individual objects. That's what we did. That's why we implemented the observer pattern (although at the time I didn't even know it by that name). I am well aware of the possible drawbacks of inheritance, but we didn't suffer any, so we had no reason to look for another solution.
KjellKod.cc wrote: (regarding performance)
If you then are unlucky enough to have an "Observer" that needs to receive several types of data and use multiple-inheritance to get it then you are on a downhill slope.
In the project I was talking about there was no notable cost for using virtual or multiple inheritance. Avoiding it wouldn't have gained us anything at all. But there was a notable cost for extra traffic between threads, context switching, waking up sleeping threads unnecessarily, and the like. Therefore minimizing communication was top priority.
I can easily see how - depending on the system you're on and the priorities you face - using virtual inheritance indiscriminately may bog down your application to a standstill. But that simply wasn't the case for us.
In the end, what pattern you should use depends on the problem at hand.
|
|
|
|

|
Stefan_Lang wrote: In the end, what pattern you should use depends on the problem at hand
Well said Stefan!
Stefan_Lang wrote:
KjellKod.cc wrote: There is nothing to stop you from using signals-n-slots and using a connect/disconnect though an interface is there?
Yes, in fact there is: As I pointed out, the connection in that case I mentioned often depended on the observers inner state. That means any external object activating or deactivating that connection would have had to be notified of a change of that state, turning it into an observer! It would be rather ironic to decouple an observer from its duty to maintain its connections by introducing an observer to that observer!
I agree to disagree [1, 2 and 3]
1. At least in the scenario that the data-stream to be shuffled by a connection is more frequent than the need for the Observer to start/stop listening to the data stream.
2. KSignal Hypotechical Technical Reasoning:
There is also the possibility of course (signal-n-slot implementation dependent) that the slot is a physical entity in your object. Owned by composition by the Observer. That's nothing to stop one from putting in an inActive_ flag in the slot to stop it from pushing the data to the Observer. Yes it would be overhead as the call to the slot would be made,. but (see below for thread discussion) in the no-thread-to-thread scenario that overhead would be minuscule.
3. Similar to 2. The Observer receives the data but has internal state that lets it to ignore it.
Stefan_Lang wrote: there was a notable cost for extra traffic between threads, context switching, waking up sleeping threads unnecessarily, and the like. Therefore minimizing communication was top priority. Ah. This is the core of the issue I think. It would be interesting to see a sketch outline of the Observer pattern you used. As the pattern in its raw form show nothing of thread-to-thread communication. Obviously the Observer pattern as shown in the article above cannot be used for thread-to-thread communication...
Qt's (the originator for the term signal-n-slot) signal-n-slot does implement safe thread-to-thread communication. In fact it is to me the only known thread-safe signal-and-slot communication scheme since it uses thread-safe "signal-message" queues towards the Qt wrapped thread. (This was going to be the next feature for ksignals. I only need a paid excuse to do it. Anyone need it with C++11? ... Please )
One "interesting" use of Observer pattern that I have seen was also done for communication between threads (and Corba-like distributed objects). They used a demultiplexor inspired way to avoid using multiple inheritance. A frequent bug that keep popping up was that non-thread-safe Subject-Observer communication was used where the more hard to use thread-Corba-safe Observer should be used. I.e. it led to two or more threads creating interesting races as they called through inheritance into other objects.
Did you guys hook up the Observer to some kind of queued message passing? Or was it up to the implementation in the Observer to have thread-safe receive of the data by using a mutex or similar?. There are a number of different way it can be done. I have seen a couple. It would be interesting to know what you guys did. It can be tricky, slow and dangerous to use inheritance to deliver messages between threads.
|
|
|
|
|
 |
|
|
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
|
This article presents the basics of Observer Pattern, when to use it and how to implement it in C++.
| Type | Article |
| Licence | CPOL |
| First Posted | 10 Feb 2012 |
| Views | 21,847 |
| Downloads | 327 |
| Bookmarked | 18 times |
|
|