Talk:Observer pattern

Page contents not supported in other languages.
From Wikipedia, the free encyclopedia

The whole basis of this article is currently incorrect[edit]

Libraries and frameworks exist for JavaScript to utilize the observer pattern, but some like RxJS are incorrectly associated with the Observer pattern. RxJS is only helping as a wrapper for upstream events like DOM click events or promises. But, the observer pattern definition that originated from the Gangs of Four is critically about the mutation of data state that requires a "Subject"[1]; RxJS cannot observe the modification of a "Subject" Javascript variable or object.

The bulk of this wiki article is inconsistent with the original definition[2] that requires an object rather than an event source. The reader should be aware that the current article currently duplicates the idea of an Event Stream. — Preceding unsigned comment added by Merarischroeder (talkcontribs) 01:11, 24 January 2021 (UTC)[reply]

You can find the following key excerpts from the original Gang of Four Design Patterns book:

  • "Whenever the subject undergoes a change in state" - this is not an event-source. Events don't have state, they are a message about an event like a user clicking a mouse
  • "In response, each observer will query the subject to synchronize its state with the subject's state" - this refers to a signal then the ability for the observer to access the current state. Unlike an event message that might hold the state at the time of the state change.
  • "The Observer pattern decouples senders (subject) from receivers (observers) by defining an interface for signaling changes in subjects" - signalling is about triggering the observer and letting it know about the state change, not passing event messages.
  • "All a subject knows is that it has a list of observers" - the subject should implement the interface

Criticism and comments for the current state of the article:

  • "in event driven software. In those systems, the subject is usually named a stream of events or stream source of events, while the observers are called sinks of events" - this has highjacked the introduction and is explicitly now talking about "event driven software". This needs paragraph needs to be removed, it's discussing other ideas separate to "Observer Patterns" without contrasting. Instead, this section should further qualify what the terms "subject" and "observers" means and stick to the topic. Also: "The Observer design pattern is one of the twenty-three well-known" - this should be in the introduction, it's the authoritative source where the term came from.
  • "Defining a one-to-many dependency between objects by defining one object (subject) that updates the state of dependent objects directly is inflexible..." - this is talking about the problems of a different solution and it has no references. It seems to be discussing performance implications of Observer vs Function calls, which should be in a Criticism section of the article.
  • "What solution does the Observer design pattern describe" - this section is actually quite accurate
  • "Strong vs Weak Reference" should be in a Criticism section of the article.
  • "Typically, the observer pattern... desired security measures" - this sections has no references, and it's easy to dismantle. "Desired security measures" don't really have bearing within an application. Observer pattern is about the coding of an application not a distributed Event-Driven architecture (which the author appears to be referring to instead). This misdirected topic focus is confirmed in the following sentence "this is solved by creating a dedicated message queue server" - that's for Event-Driven architecture, not the canonical Observer pattern. "subscribing to certain messages" - the Observer pattern talks about Signalling, not messages; they are very different mechanisms.
  • "were used as a synonym for the observer pattern" - the linked reference does not mention even the word "observer". It does explicitly mention "Event-Driven Architecture" however. The synonym was only in the author's subjective mind.
  • the "Uncoupled" section does not have any references. It also continues the incorrect correlation of Window Messages to Observer pattern. Window Messages are of course a good example of the broader asynchronous/reactive programming approach, but the Observer Pattern is a very specific way to implement that, and Window Messages are not implemented that way.
  • The UML first class and sequence diagram pictured is fine - it shows the Subject has got state that is accessed by Observer instances.
  • The second UML class diagram is incomplete and should be removed - it doesn't show the "query" of state after being signalled.
  • The Java example is incorrect: it is sourced from an upstream synchronous transient event, the return value of "nextLine". That isn't a mutation of object state.
  • The Groove example is also incorrect, it is basically a transpiling of the Java example
  • The Kotlin example is also incorrect, it is basically a transpiling of the Java example
  • The Delphi example is incorrect: it doesn't even subscribe to a natural event, but instead an Example button, where AddObserver is called. So it's 2x wrong.
  • The Python example is incorrect in the same way as the Delphi example
  • The C# example is incorrect: it has a "message" payload which is an Event-Driven concept, not Observer Pattern. The Subject doesn't have any internal data state, instead it's used as a Publish point with SendMessage to the Subscribed objects.
  • I have updated the Javascript example to be correct today. — Preceding unsigned comment added by Merarischroeder (talkcontribs) 02:13, 24 January 2021 (UTC)[reply]

References

Implementation flaw in C++[edit]

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)[reply]

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)[reply]

=======Another Implementation Flaw in C++==================[edit]

This line of code inside main() registers subscriber with the publisher:

  str.add(refl);

It is done through the publisher's member function called by publisher object that takes a reference to a subscriber object. Publisher should not be aware about how many subscriber objects are out there (if any) - subscriber should be the one who initiates the subscription. So this process should be implemented with the subscriber's member function and initiated by the subscriber. Internally a publisher's member function should be called via pointer to the publisher stored in the subscriber. For example:

  void listener_observer::RegisterWithPublisher()
  {
     //pPublish is a pointer to the publisher
     //AddUpdatePointer - Publisher's member function that stores subscriber's pointer to the list
     pPublish->AddUpdatePointer((void*)this);
  }

UML diagram[edit]

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 (talkcontribs) 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 (talkcontribs) 09:36, April 3, 2006 (UTC)

The image is not valid UML: The line connecting the code comment to the notify method is missing a circle on the end. Further, while it is grammatical to say that a subject is composed of its observers, it's a moronic thing to say. I'm referring to the line connecting the observer with the subject. That should be a simple association. Multiplicities on that line would help. The class boxes contain an empty attribute field, which is superfluous. 130.92.9.58 (talk) 11:27, 22 July 2010 (UTC)[reply]

needs a section on deadlocks?[edit]

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)[reply]

Wouldn't that be more of a livelock, actually? –Johannes Rössel (talk) 06:16, 13 May 2009 (UTC)[reply]

subject vs. object[edit]

"... 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)[reply]


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[edit]

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).[reply]

- Strongly agreed. Now if someone cared enough to change the diagram...

Agreed if that's whats in the source. We need a link to such source evidence to add as references, please include here. I'm happy to make a new diagram to make it "more accurate". --Merarischroeder (talk) 02:28, 24 January 2021 (UTC)[reply]

Gang of Four Diagrams are NOT UML and they NEVER WERE![edit]

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".

OK, GOF didn't use UML. No one said they did but anyway that's sorted. 81.187.215.34 (talk) 23:04, 1 July 2016 (UTC)[reply]

How to get the perfect diagram - Reverse Engineering[edit]

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[edit]

  • 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[edit]

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 (talkcontribs) 09:23, 1 February 2008 (UTC)[reply]

I disagree. The term "Observer Pattern" is a noun first used and defined in Design Patterns (Gang of Four). It objectively has a specific description and narrow specification for implementation. Who invented this (Signalling with subsequent query of state by observer)? Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides When? Around 1994 --Merarischroeder (talk) 02:26, 24 January 2021 (UTC)[reply]

Implementation refactor[edit]

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)[reply]

Implementation flaw in Python[edit]

The dictionary should be composed in the Observable class not inherited. http://wiki3.cosc.canterbury.ac.nz/index.php/Avoid_inheritance_for_implementation —Preceding unsigned comment added by 125.236.134.253 (talk) 08:20, 3 December 2009 (UTC)[reply]

Is the pseudocode syntax really Pythonesque, or just similar to that of Python? Sciamachy (talk) 13:34, 27 November 2007 (UTC)[reply]

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)[reply]

observer[edit]

The observer's method should NOT be notify() that is totally confusing to new users. Use 'update'. This is really bad.

I disagree, the canonical source for this pattern describes signalling where the observer then queries to get the state. Update would be the incorrect name. Notify or Signal are more suitable. --Merarischroeder (talk) 02:23, 24 January 2021 (UTC)[reply]

Bad implementation in Java[edit]

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)[reply]

C# implementation: abstract Subject[edit]

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)[reply]

Insanity[edit]

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)[reply]

No one is in charge of the article. Your vandalism attempts are reverted by different editors. Creating a 'wrong' diagram is not a crime as you keep saying. Try to get some perspective, is it really likely that it's everyone else that's insane? 81.187.215.34 (talk) 22:22, 1 July 2016 (UTC)[reply]

Agreed. Gang of Four is the canonical reference. There is no opinion to be made, ADD and NOTIFY are the canonical interfaces for this pattern, and authors should not be allowed to deviate from objective fact. --Merarischroeder (talk) 02:17, 24 January 2021 (UTC)[reply]

Something is seriously wrong.[edit]

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)[reply]

Agreed. Gang of Four is the canonical reference. There is no opinion to be made, ADD and NOTIFY are the canonical interfaces for this pattern, and authors should not be allowed to deviate from objective fact. --Merarischroeder (talk) 02:17, 24 January 2021 (UTC)[reply]

Request for Diagram[edit]

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)[reply]

C#/.NET doesn't need Interfaces for Observer Pattern[edit]

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)[reply]

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)[reply]

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)[reply]

Merge with Publish/subscribe[edit]

[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)[reply]

Observer pattern is not the same thing as Publish/Subscribe. Gang of Four is the canonical reference. --Merarischroeder (talk) 02:18, 24 January 2021 (UTC)[reply]

If GoF is the canonical reference, they describe Publish/Subscribe as an alias for Observer. 64.234.88.136 (talk) 15:41, 17 May 2022 (UTC)[reply]

Too many articles?[edit]

Please see my discussion on Talk:Publish/subscribe#Too_many_articles.3F. Thank you. Quilokos (talk) 00:15, 4 July 2009 (UTC)[reply]

The BASIC part[edit]

There's nothing in the BASIC part, so I just remove it. — Preceding unsigned comment added by 115.133.109.229 (talk) 13:53, 28 May 2011 (UTC)[reply]

Java Example[edit]

The java code as of date is using an observer library, but doesn't really explain how the actual pattern is implemented which should be the point of the article. --Popoi (talk) 17:27, 29 November 2012 (UTC)[reply]

Unnecessary if() or (cast) & public ObserverCollection[edit]

This page is still relevant because people use this wikipedia page for studying.

In this piece of code, the if checks if the arguments passed through are an instance of String, then casts it to a String.

if (arg instanceof String) {

  resp = (String) arg; 
  System.out.println("\nReceived Response: " + resp ); 

}

However, it seems unwise to check if a String is passed through because when people do not insert a String, the casting seems pointless and nothing will happen anyway. Is there a reason for this?

Also, why is the Collection of Observers public, as the public methods are used to manipulate it?

Lambda function[edit]

Could somone PLEASE change the Java example code so as not to use a lambda function? This construct is quite new to Java and just makes the code opaque rather than clarifying. If you are writing pedagogical code it surely MUST be the simplest possible, requiring the least prerequisite knowledge! There seems to be no Wikipedia article on the Java lambda function.

Cheers. — Preceding unsigned comment added by 82.45.163.65 (talk) 20:18, 15 June 2016 (UTC)[reply]

I've changed it to an inner class instead. 81.187.215.34 (talk) 23:10, 1 July 2016 (UTC)[reply]

UML class and sequence diagram[edit]

I have shared the following UML diagrams I have published on Design Patterns Open Online Learning. Your comments are welcomed.

A sample UML class and sequence diagram for the Observer design pattern.

In the above UML class diagram, the Subject class doesn't update the state of Observer1 and Observer2 directly. Instead, Subject refers to the Observer interface for updating (synchronizing) state (for each o in observers: o.update()), which makes the Subject independent of how (and how many) observers are updated. The Observer1 and Observer2 classes implement the Observer interface by updating their state (synchronizing their state with subject's state).

The UML sequence diagram shows the run-time interactions: The Observer1 and Observer2 objects call attach(this) on Subject1 to register themselves. Assuming that the state of Subject1 changes, Subject1 calls notify() on itself.
notify() in turn calls update() on the registered Observer1 and Observer2 objects, which in turn get the changed data (getState()) from Subject1 to update (synchronize) their state.
Vanderjoe (talk) 22:08, 20 August 2017 (UTC)[reply]


The activity diagram is wrong, the observer shouldn't have an attach method.85.150.231.254 (talk) 16:24, 13 July 2018 (UTC)[reply]

Attach is close enough to "Add". This is a good diagram, it could be improved to be consistent with the same method names mentioned by the Gang of Four which is the canonical reference. --Merarischroeder (talk) 02:20, 24 January 2021 (UTC)[reply]

The UML diagrams do not match the code[edit]

The diagrams show something completely unrelated to the code, the functions prototypes and class relations don't match. — Preceding unsigned comment added by 85.150.231.254 (talk) 16:22, 13 July 2018 (UTC)[reply]

This is because the code is incorrect. The canonical Gang of Four Design Patterns publication is where this pattern came from, and the UML diagram is very close to that. The code examples are only Pub/Sub examples, they don't implement any "state" to be observed. --Merarischroeder (talk) 02:21, 24 January 2021 (UTC)[reply]

This article is a little off piste[edit]

I agree with the previous comment. I think this article seems to be written from the perspective of reactive streams. More than once I've come across a reactive streams developer who has assumed that RxJava invented the observer pattern. But obviously that's incorrect and this article makes things extremely muddy and confusing for someone just wanting to know what the observer pattern is. Most of it should be deleted IMO, and the rest of it should hew closer to GOF info 77.136.103.17 (talk) 16:34, 13 November 2022 (UTC)[reply]