O'Reilly logo

C# 3.0 Design Patterns by Judith Bishop

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required