Observer Pattern
[Download cs c#]Definition
Define
a one-to-many dependency between objects so that when one object changes state,
all its dependents are notified and updated automatically.
//Observer Class
abstract class Observer
{
public abstract void Update();
}
//Subject Class
abstract class Subject
{
private List<Observer> _observer = new
List<Observer>();
public void Register(Observer obs)
{
_observer.Add(obs);
}
public void
Unregister(Observer obs)
{
_observer.Remove(obs);
}
public void Notify()
{
foreach (Observer
obs in _observer)
{
obs.Update();
}
}
}
//StockMarket Class
class StockMarket
: Subject
{
private string
_subjectState;
public string
SubjectState
{
get
{
return _subjectState;
}
set
{
_subjectState = value;
}
}
}
//GoogleStockGadet Class
class GoogleStockGadet : Observer
{
private string _name;
private string
_observerState;
private StockMarket
_concreteSubject;
public GoogleStockGadet(StockMarket
conSubject, string name)
{
_concreteSubject = conSubject;
_name = name;
}
public override void Update()
{
_observerState = _concreteSubject.SubjectState;
Console.WriteLine("Observer
{0}'s new state is {1}", _name, _observerState);
}
public StockMarket
Subject
{
get
{
return _concreteSubject;
}
set
{
_concreteSubject =
value;
}
}
}
//MSNStockGadget Class
class MSNStockGadget : Observer
{
private string _name;
private string
_observerState;
private StockMarket
_concreteSubject;
public MSNStockGadget(StockMarket
conSubject, string name)
{
_concreteSubject = conSubject;
_name = name;
}
public override void Update()
{
_observerState = _concreteSubject.SubjectState;
Console.WriteLine("Observer
{0}'s new state is {1}", _name, _observerState);
}
public StockMarket
Subject
{
get
{
return _concreteSubject;
}
Set
{
_concreteSubject = value;
}
}
}
//YahooStockGadget Class
class YahooStockGadget : Observer
{
private string _name;
private string
_observerState;
private StockMarket
_concreteSubject;
public YahooStockGadget(StockMarket
conSubject, string name)
{
_concreteSubject = conSubject;
_name = name;
}
public override void Update()
{
_observerState = _concreteSubject.SubjectState;
Console.WriteLine("Observer
{0}'s new state is {1}", _name, _observerState);
}
public StockMarket
Subject
{
get
{
return _concreteSubject;
}
Set
{
_concreteSubject = value;
}
}
}
//Calling...
StockMarket s = new
StockMarket();
s.Register(new GoogleStockGadet(s,
"X"));
s.Register(new MSNStockGadget(s,
"Y"));
s.Register(new YahooStockGadget(s,
"Y"));
s.SubjectState = "ABC";
s.Notify();
0 comments:
Post a Comment