Demonstration of Observer pattern using a Timer


if you are want to about Observer pattern then this article explain difference between objects changes state, all its dependents are notified and updated automatically.

Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. The .NET Timer class can be used to demonstrate this pattern. A class called Stock which simulates a Stock quote is designed which starts a Timer internally. A parallel interface called Observer is designed. Any class which implements this interface and registers with a Stock object will be notified periodically of the stock quotes. The Stock class maintains the list of registered Observer objects in an ArrayList.

Here is the Stock Class


public class Stock
{
private ArrayList observers = new ArrayList();
private Random rand = new Random();

public Stock()
{
Timer timer = new Timer(3000);
//Register an ElapsedEventHandler which will periodically triggere GeneratePrice
timer.Elapsed +=new ElapsedEventHandler(GeneratePrice);
timer.Start();
}

public void register(Observer anObserver)
{
observers.Add(anObserver);
}

private void GeneratePrice(object sender, ElapsedEventArgs e)
{
double price = rand.NextDouble() * 100;
// We will notify the observers now
foreach(Object o in observers)
{
Observer anObserver = o as Observer;
anObserver.update(price);
}
}
}

Here is the contractual interface bewteen the Stock class and its observers

public interface Observer
{
void update(Object data);
}

Define a class called StockMonitor which implements the Observer interface

public class StockMonitor : Observer
{
public void update(Object data)
{
Console.WriteLine("Price is " + data);
}
}

Here is a little test code:

Stock s = new Stock();
StockMonitor m = new StockMonitor();
s.register(m);


Comments

Guest Author: raghu20 Aug 2012

I had a question , since observer is an interface , how is it possible that we are instantiatiating the interface ???
Observer anObserver = o as Observer;



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: