Observer Pattern using C# Delegate
class Program
{static void Main(string[] args)
{
Stock stock1 = new Stock("IPCL");
stock1.Price = 27.10M;
StockObserver1 so1 = new StockObserver1();
StockObserver2 so2 = new StockObserver2();
//Register Observers with the subject
stock1.Registor(so1);
//Register Observers with the subject
stock1.Registor(so1);
stock1.Registor(so2);
stock1.Price = 31.59M;
//Unregister Observers (StockObserver1) from the subject
//Unregister Observers (StockObserver1) from the subject
stock1.UnRegistor(so1);
stock1.Price = 41.59M;
Console.Read();
}
}
class Stock : ISubject
{
public string Symbol { get; set; }
private Decimal price;
public Stock(string str)
{
Symbol = str;
}
//Declare an event of type delegate of void method with string parameter
public event Action<string> PriceChanged;
//Declare an event of type delegate of void method with string parameter
public event Action<string> PriceChanged;
public virtual void OnPriceChanged()
{
if (PriceChanged != null)
PriceChanged(string.Format("Stock {0} price changed {1}",
Symbol, Price.ToString()));
}
public Decimal Price
{
get { return price; }
set
{
if (price == value)
return;
price = value;
OnPriceChanged();
}
}
public void Registor(IObserver obj)
{
//attaching to the delegate with observer update method
//attaching to the delegate with observer update method
PriceChanged += obj.update ;
}
public void UnRegistor(IObserver obj)
{
//dettaching the delegate with observer update method
//dettaching the delegate with observer update method
PriceChanged -= obj.update;
}
}
interface IObserver
{
void update(string obj);
}
interface ISubject
{
void Registor(IObserver obj);
void UnRegistor(IObserver obj);
}
public class StockObserver1 : IObserver
{
public void update(string obj)
{
Console.WriteLine("StockObserver1 stok changed" + obj);
}
}
public class StockObserver2 : IObserver
{
public void update(string obj)
{
Console.WriteLine("StockObserver2 stok changed" + obj);
}
}
Good work. it would be better if you can add some comment for visitors. Happy programming :)
ReplyDelete