Talk:Observer pattern
![]() | Computer science Start‑class Mid‑importance | ||||||||||||||||
|
Implementation flaw in C++
The example implementation in C++ is good, but it contains a small flaw: if an additional concrete observer is added that inherits from ObserverBoardInterface, but NOT from DisplayBoardInterface (or vice versa), the code will crash. One way to address this would be to add a new member variable to ParaWeatherData like so:
list<DisplayBoardInterface*> m_disp;
along with these new functions:
void registerdisp(DisplayBoardInterface* disp) { m_disp.push_back(disp); } void removedisp(DisplayBoardInterface* disp) { m_disp.remove(disp); }
Then change the function notifyOb() to iterate through each list separately, calling the appropriate fns in each case. Of course, the constructors in the concrete observer classes would need to be updated as well. I'm new to this, so if there is a simpler adjustment that would work, I'd love to hear it. Kmote (talk) 22:29, 15 December 2008 (UTC)
I found the DisplayBoardInterface just confused things - is it even needed in this example? The concept is illustrated without it - I would remove the DisplayBoardInterface class and the show function and move the printing into the update function. —Preceding unsigned comment added by 89.181.85.191 (talk) 15:21, 2 April 2009 (UTC)
UML diagram
Short comment on the image: Since the subject class has to notify several observers, an asterix is missing in the UML diagram in order to indicate multiplicity! —The preceding unsigned comment was added by 89.49.166.151 (talk • contribs) 11:24, February 18, 2006 (UTC)
Do you really want a picture of Asterix there? Or perhaps an asterisk? :) —The preceding unsigned comment was added by 199.172.169.17 (talk • contribs) 09:36, April 3, 2006 (UTC)
needs a section on deadlocks?
I think the article needs a section about possible deadlocks (two or more objects observing each other and updating in an infinite loop), and possible solutions to this deadlock problem. 80.57.251.230 (talk) 22:27, 2 December 2008 (UTC)
- Wouldn't that be more of a livelock, actually? –Johannes Rössel (talk) 06:16, 13 May 2009 (UTC)
subject vs. object
"... event which may be raised by the observed object (the subject). (The object which may raise an event generally maintains a collection of the observers.)" Isn't the sentence "An object listens for a subject" aganst of language grammar rules? Why not to exploint the conventional terminology: event source/publisher fires an event to event listeners/susbcribers or invokes them to observe the event? --Javalenok 11:38, 10 October 2006 (UTC)
The Qt librairy does not implements the observer pattern at all. It uses pre compiler directives and C-style function pointers which isn't even object oriented. The note about Qt should be removed
GOF consistency
The UML diagram should use the naming convention from GOF. Specifically the notify() method in the **Subject** looping through its Observers and calling the **update()** method in those Observers. Having a notify() method in the Observer is confusing, it should be called update(). —The preceding unsigned comment was added by 68.175.22.82 (talk) 19:31, 8 December 2006 (UTC).
- Strongly agreed. Now if someone cared enough to change the diagram...
Gang of Four Diagrams are NOT UML and they NEVER WERE!
Before we get to the diagram somebody mentioned above, sadly deleted now. I remember basing my code on it and it was exact and correct UML2 notation - the person who put it in originally was correct. First a few very strong words based on fact and history:
GoF desperately needs to be updated - but that is no excuse. With reference to UML in GoF and the collection of above people strongly agreeing with each other! First there is NO UML IN Gang of Four - NO NOT ANY! The book Design Patterns: Elements of Reusable Object-Oriented Software, Enrich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, Addison-Wesley, 1995" predates UMLs first release. The diagrams are all in OMT Object Modeling Technique which is now 11 years out of date and UML version 1 is NOT MENTIONED AT ALL IN THAT BOOK and so is not used for the diagrams. Software architects are now using UML version 2! This does not invalidate that bible, and it was intended to be read by clever design people who are also capable of hatching their very own patterns (see the book Pattern Hatching by John Vlissides one of the gang of four himself). UML was based on a form of Rumbaugh OMT and Booch Method as well as many other types of representation techniques, so reading GoF as part of a UML course confuses the uneducated easily. UML pre-release as a white paper was however published about that time.
I noticed with great annoyance that some of the other design pattern wiki entries use the OMT format which can not be entered into Enterprise Architect (for example) because the UML2.0 validation quite rightly rejects them - (the validation is not super strict because UML2 allows flexibility and design creativity of methodology representations ). I must stress to my critics that Enrich Gamma, Richard Helm, Ralph Johnson, and John Vlissides as well as famous design pioneers like Grady Booch and the prime inventor of OMT James Rumbaugh (retired 18 months ago) all use modern UML2. Many so called UML articles on the web show GoF diagrams exactly as in their book, box for box and word for word a case of blatant plagiarism - lacking all original effort and design imagination, especially lacking intellectual rigor with regard to UML.
So yes please go along with the famous Gang of Four but please actually use Unified Modeling Language 2.0 terminology and of course use those authors terminologies too WITHOUT REPUBLISHING THEIR CHAPTERS - best leave out the 11 year old Object Modeling Technique! Please look up Grady Booch, and Object Modeling Technique then compare to UML.
If you think that GoF is rigorous UML2 notation as somebody obviously does think (above) then it is best to come back in a few years! Ask yourself if it is a good idea to update any wiki Design Pattern in this encyclopedia if you are not capable of inventing your own patterns for which there are potentially thousands. It is just as easy for those people to create anti-patterns - see the entry "anti-patterns".
How to get the perfect diagram - Reverse Engineering
UML reverse engineering tools are an easy way of bringing an end to all the OMT diagram confusion. It is a real pain to see over and over OMT versions of class diagrams 11 years after OMT died. In GoF, their Observer Pattern chapter is one of the most useful and most commonly used. It relates to the "The Hollywood Principle" which is "I'll call you, don't call me!" and it is even possible to implement it in C with very simple pointers to functions ie "callbacks" where the pointer to function is an arguments passed to the subject dynamically (i.e. by subscription or registration); often used for multi-threaded systems.
Anyway thank goodness for the C++ code in that book because from that we can generate GoF UML2 class diagrams and sequence diagrams too (NOT OMT). Reverse engineered code similar to but not the same as the Observer pattern code in that chapter. 'Similar' only because I am rightly shy of simply regurgitating that exact code but also because it needs modernizing to the style Scott Meyers and Herb Sutter, remember that C++ has changed a lot since 1995. Reverse Engineering is cheating but I hope you agree; it is accurate to the last detail. Try it if you do not believe me. It certainly is a way of proving correct UML2 Observer Pattern Class Diagram, and obviously the code must go alongside those two diagrams. (Tools include "Borland Together", "Rational Rose", Rose-RT, "Enterprise Architect" and "Telelogic Rhapsody". There are others some free some trial versions. THEY WORK VERY WELL. Microsoft purchased "Visio" and that does not work for me.) tjc.
Post Removed
- I removed a post asking for help with a design pattern. This page is for discussing changes to the main article. It is not a help forum.
History
Who invented this design pattern? When?
Answer: Like most patterns they are older than time itself and can be found in atomic physics, quantum mechanics, biological processes, genetics, animal behavior etc.
It is an interesting question because almost all programmers for the last 40 years or more have used design patterns and idioms without realizing it and often they use anti-patterns too which means that the software appears to work but end up full of bugs. Certainly the observer pattern was used by myself in Bell Labs telecommunications long before Gamma et la published their book, we just called it the callback technique. I learned that technique from games programmers that are now mostly dead and some of these chaps predated UNIX. The real answer is strange and mind boggling.
In MIT, C was used in an object oriented way to write UNIX X-Windows and again this "callback" technique was used in an OOP style in C (not C++) because C++ did not exist. RPC (Remote Procedure Calls) on UNIX existed since the 1970s.
Reality is however stranger than you can imagine. The more generic answer is that the observer pattern is not just a computer science pattern at all. Look up design patterns. To prove my point Stroustrup the creator of C++ said that "C++ allows you to model real world problems using higher conceptual levels and to use higher levels ofabstraction or abstract techniques." So these obviously include simple idioms and more abstract design patterns. He used the words "real world" and indeed most if not all patterns exist in the real world outside computer science. The test of this is simple:
If you can simulate the problem on the computer and use the pattern to clearly and beautifully solve the problem and that pattern is reusable for a variety of similar problems - then you have a pattern. A pattern is more than just a simple solution to a problem it must be non-trivial and repeatably applicable with successful results in different environments.
It is important to understand that patterns can be manufactured to solve a specific problem in a specific environment and then can be recognized and reused more formally with names being given to them. These patterns do not need to be computer science patterns and many of them are ordinary complex problems that already have solutions so the patterns are already there and already discovered. GoF gave them names and there are thousands to be discovered. Non Computer Science design patterns have been around for as long as man could design anything and you can computerize these patterns, they were used by the Egyptians to build pyramids over 3000 years ago obviously without computers but with mathematical models and formula. The observer pattern is not as strange as you think it is, but it is as old as time itself.
You can take it back even further than man. The idea of a biological process, or a genetic process or a group of social animals or insects these also use patterns some much cleverer than the observer pattern. Take a colony of meerkats where there is a division of labour, one animal is the "look out" while the others dig for insects. That look out animal is selected or self selects to be the subject up a tree and the others stay near by as observers. The lookout can spot an eagle, banded cobra or jackal and sound the alarm; even a different alarm, one for each threat; then they all either run to fight the snake or dive for cover underground, depending on the message. It's not hard to fit the observer pattern and other patterns into that? If you think that is far fetched you can easily simulate that behavior and implement the simulation using the observer pattern and other patterns! You can take the simulation and use it as the framework for a video game. —Preceding unsigned comment added by Tjclutten (talk • contribs) 09:23, 1 February 2008 (UTC)
Implementation refactor
The C# and Java implementations could both go into one subsection. Perhaps it could start with the pseudocode and then proceed to each implementation like so:
- Pseudocode - Examples - C# - Java
If someone else agrees I'll make the changes. --arkul 22:13, 26 August 2007 (UTC)
Is the pseudocode syntax really Pythonesque, or just similar to that of Python? Sciamachy (talk) 13:34, 27 November 2007 (UTC)
- Simply add underscores around the
init
methods and it runs in Python 2.5... I've refactored this a bit. --Mrwojo (talk) 23:28, 2 March 2008 (UTC)
observer
The observer's method should NOT be notify() that is totally confusing to new users. Use 'update'. This is really bad.
Bad implementation in Java
This implementation broke two general principles of object-oriented design with Java. Explanations: [1] —Preceding unsigned comment added by 132.217.93.123 (talk) 20:29, 7 July 2008 (UTC)
C# implementation: abstract Subject
Shouldn't the Subject class be defined as abstract and the Operate() method moved to it's own class, to have a better encapsulation? 85.127.185.133 19:42, 16 October 2007 (UTC)
Insanity
The insanity of this article continues. Whoever is in charge of this article needs to stop.
It is not attach detach. STOP THE MADNESS. removing observers is not an integral part of the pattern. yes, it should be discussed later on, BUT IS NOT IN THE PRIMARY DEFINITION. READ GOF. WHAT IS YOU PROBLEM?
ADD and NOTIFY -- thats it. Stop inventing your own language and notation. something is seriously deeply wrong with you. —Preceding unsigned comment added by 38.96.160.34 (talk) 16:14, 21 February 2008 (UTC)
Something is seriously wrong.
Im not really clear on why this article is CONSISTENTLY WRONG, but whoever keeps A) making the diagrams, and B) describing it is NOT QUALIFIED to talk on the subject.
OPEN GOF, read about it, and then learn something. —Preceding unsigned comment added by 38.96.160.34 (talk) 16:17, 21 February 2008 (UTC)
Request for Diagram
I've requested that a diagram be made available for this article. After reading through this page I think it's only fair to remind people that arguing with people on the internet is like competing in the Special Olympics (for want of a better phrase). If you find something incorrect on Wikipedia then by all means change it! Bactoid (talk) 02:11, 3 June 2008 (UTC)
C#/.NET doesn't need Interfaces for Observer Pattern
Quite honestly everyone, the Observer pattern is built into the event system that is implemented as part of the .NET Framework. Events are published by the subject and n observers are able to attach and detach/add and remove to the events as needed. Further, only the concrete subject is able to directly notify for the events - descendant classes cannot access the published events except through an intermediary. Here's a quick example:
class Button { public event EventHandler Clicked; protected virtual void OnClicked(EventArgs e) { if (Clicked != null) Clicked(this, e); } } class LinkButton : Button { private void HandleMsg(ref MSG m) { if (m.Message == MessageIDs.Click) // attempting to call Clicked() directly would result in a compile-time error. OnClicked(EventArgs.Empty); } }
Now, any other object with a reference to a Button or LinkButton is able to subscribe to the Clicked event. The only difference between standard Observer and .NET's implementation is that a concrete observer is not required -- the concrete observer is mediated by the method signature declared as part of the event (EventHandler) instead of an interface.
If nobody objects, I'll make the appropriate notes within the C# section in the next few days. Robert Paveza (talk) 01:52, 8 September 2008 (UTC)
This goes for the ActionScript example as well. ActionScript has Event Dispatching in its core, so the AS example could be very similar to the C# example using events. --85.24.240.236 (talk) 12:11, 21 March 2009 (UTC)
- I think it'd be worth mentioning that some languages have direct support for this built into the language (as is the case with some more patterns, actually), but the example would show how to roll your own implementation in the specific language (which may not be advisable but would show how to do it, if you're so inclined). Simply using the language's mechanism in this article might be confusing as at least for C# it doesn't really bear much resemblance to the pattern as outlined by the GOF.
- Furthermore you have an error in your examples of using events in C#. You need to create a copy of the event handlers (which are multicast delegates) before using them, as you could create a race condition where another thread removes the last event handler after the check for null, but before the invocation of the delegate:
protected virtual void OnClicked(EventArgs e) { var clickedCopy = Clicked; if (clickedCopy != null) clickedCopy(this, e); }
- This is also outlined in MSDN and has been written about by Eric Lippert —Johannes Rössel (talk) 06:25, 13 May 2009 (UTC)
Merge with Publish/subscribe
[2] considers the Observer pattern and Publish/Subscribe to be the same thing. Some may consider the Observer object to be one participant (the "broker") in Publish/Subscribe, but that doesn't seem like a good reason to have a separate article. -- Beland (talk) 23:41, 14 May 2009 (UTC)
Too many articles?
Please see my discussion on Talk:Publish/subscribe#Too_many_articles.3F. Thank you. Quilokos (talk) 00:15, 4 July 2009 (UTC)