Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Observer is a means of decoupling, that is, loosening the connections between two objects. You want that because it makes your code neater and easier to maintain. That's pretty much the goal of all design patterns: easier to read, easier to maintain code.</p> <p>In this pattern, you have two classes, two objects: publisher and observer. Publisher is a class that actually does some work, then it every so often will call methods on any observers to tell them about it. It knows which classes to call because it keeps a list of observers who subscribed.</p> <p>So your Publisher might look something like this:</p> <pre><code>class Publisher { List&lt;Observer&gt; observers = new List&lt;Observer&gt;(); public Add(Observer o) { observers.Add(o); } private AlertObservers() { foreach(Observer o in observers) { o.Alert(); } } </code></pre> <p>Publisher really does most of the work. All the Observer needs to do is get added to the list and implement the called method. Like so:</p> <pre><code>class Observer { public Observer(Publisher pub) { pub.Add(this); } public Alert() { System.Console.WriteLine("Oh no, stuff is happening!"); } } </code></pre> <p>That's a pretty barebones idea of how it works. Now, why is that valuable? Looks pretty well coupled up huh? One reason for that is because I don't use an Interface, which would allow me to set up many classes with Observer functionality, and Publisher need never know anything more about them except that they can receive an Alert() call. Also note that Publisher will attempt to call Alert on any and all Observers it has, even if it has none. </p> <p>Now, in the C# world, the language has a built in version of this pattern through it's Event objects. Events are very powerful and make use of Delegates, which is a way of passing a method as a parameter in another method call. They allow for some serious decoupling, but I'd save that for a new question.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload