Observing the Observer Pattern
Chris Missal, December 20, 2008
In my quest to improve my skills as a programmer, and moreover improve my understanding of patterns and practices, I wrote up a quick sample on the Observer pattern. At work, we're demoing a pattern a week to keep fresh on architectural principles. On Wednesday of this week, I presented a demo I wrote up that shows a simple example.
The code samples below are the basica concepts of the pattern. You have one object (the Observer) that "observes" a subject. The subject being observed in this code is an OrderService.
1 public interface IObserver 2 { 3 OrderService Subject { get; set; } 4 5 void Update(); 6 } 7
The OrderService should implement the IObservable interface:
1 public interface IObservable 2 { 3 void Attach(IObserver observer); 4 5 void Detach(IObserver observer); 6 7 void Notify(); 8 } 9
To finish putting all the pieces together, we need our Subject, the OrderServce, to do something with the IObservable interface:
1 public class OrderService : IOrderService, IObservable 2 { 3 public void Notify() 4 { 5 foreach (var observer in observers.Values) 6 { 7 observer.Subject = this; 8 observer.Update(); 9 } 10 } 11 12 public void Submit(Order order) 13 { 14 // do whatever the OrderService.Submit does.. 15 Notify(); 16 } 17 }
The OrderService Notifies its Observers when it Submits an Order. This pattern can take on many usages like firing events and works in a similar way as Messaging Systems.
To see the code view the SVN repository.
Filed Under: .Net C# Open Source Observer Pattern













