Observer Pattern Example Code—Blogs

See the following code for an example of the Observer Pattern:

using System; using System.Collections.Generic; using System.Collections; using System.Threading; using System.Windows.Forms; using System.Drawing; class ObserverPattern { // Observer Pattern Judith Bishop Sept 2007 // Demonstrates blog updates. Observers can subscribe and unsubscribe // online through a GUI. // State type public class Blogs { public string Name {get; set;} public string Topic {get; set;} public Blogs (string name, string topic) { Name = name; Topic = topic; } } public delegate void Callback (Blogs blog); // The Subject runs in a thread and changes its state // independently by calling the Iterator // At each change, it notifies its Observers // The Callbacks are in a collection based on blogger name class Subject { Dictionary <string,Callback> Notify = new Dictionary <string,Callback> ( ); Simulator simulator = new Simulator( ); const int speed = 4000; public void Go( ) { new Thread(new ThreadStart(Run)).Start( ); } void Run ( ) { foreach (Blogs blog in simulator) { Register(blog.Name); // if necessary Notify[blog.Name](blog); // publish changes Thread.Sleep(speed); // milliseconds } } // Adds to the blogger list if unknown void Register (string blogger) { if (!Notify.ContainsKey(blogger)) { Notify[blogger] = delegate {}; } } public void Attach(string blogger, Callback Update) { Register(blogger); Notify[blogger] += Update; } public void Detach(string blogger, Callback ...

Get C# 3.0 Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.