I am implementing observer pattern(refering codeproject) for stock quote update. I have created an interface for Subject and Observer. I have created instances for Subject and Observer and also the functionality to register, notify and update. Kindly let me know the approach is correct
public interface IObserver
{
void update(double value);
}
}
//subject
public interface ISubject
{
void Register(IObserver o);
void UnRegister(IObserver o);
void notify();
}
//Observer instance
public class InfosysStock : IObserver
{
private ISubject _subject;
private double _latestvalue = 0;
public InfosysStock(ISubject subject)
{
_subject = subject;
_subject.Register(this);
}
public void update(double value)
{
_latestvalue = value;
display();
}
private void display()
{
Console.WriteLine("The latest value is : " + _latestvalue);
}
public void unsubscribe()
{
_subject.UnRegister(this);
}
}
//Subject Instance
public class StockMarket : ISubject
{
List<IObserver> observers = new List<IObserver>();
public int _stockvalue = 0;
public void setValue(int v)
{
_stockvalue = v;
notify();
}
public void notify()
{
foreach (var observer in observers)
{
observer.update(_stockvalue);
}
}
public void Register(IObserver o)
{
observers.Add(o);
}
public void UnRegister(IObserver o)
{
int idx = observers.IndexOf(o);
observers.RemoveAt(idx);
}
}
Finally the main class
StockMarket stockmarket = new StockMarket();
InfosysStock infy = new InfosysStock(stockmarket);
stockmarket.setValue(15);
stockmarket.setValue(21);
infy.unsubscribe();
Console.ReadLine();
setValue
should automatiacally notify listeners. Having to callnotify
manually is pointless and makes the whole pattern unnecessary. \$\endgroup\$