Mediator:
The
mediator pattern encapsulate the interaction between a set of
objects.
class Program
{
static void Main(string[] args)
{
IBM ibm = new IBM("IBM", 150.00);
ibm.Attach(new Investor("aaa"));
ibm.Attach(new Investor("bbb"));
//Fluctuating prices will notify investors
ibm.Price = 150.00;
ibm.Price = 152.00;
ibm.Price = 130.00;
Console.ReadKey();
}
}
interface IInvestor
{
void Update(Stock stock);
}
class Investor : IInvestor
{
private string _name;
private Stock _stock;
public Investor(string name)
{
_name = name;
}
public void Update(Stock stock)
{
Console.WriteLine("Notified {0} of {1} 's change to {2:c}", _name, stock.Symbol, stock.Price);
}
public Stock Stock
{
get { return _stock; }
set { _stock = value; }
}
}
abstract class Stock
{
private string _symbol;
private double _price;
private List<IInvestor> _investors = new List<IInvestor>();
public Stock(string symbol, double price)
{
this._symbol = symbol;
this._price = price;
}
public void Attach(IInvestor investor)
{
_investors.Add(investor);
}
public void Detach(IInvestor investor)
{
_investors.Remove(investor);
}
public void Notify()
{
foreach (IInvestor investor in _investors)
{
investor.Update(this);
}
}
public double Price
{
get { return _price; }
set
{
if (_price != value)
{
_price = value;
Notify();
}
}
}
public string Symbol
{
get { return _symbol; }
}
}
class IBM : Stock
{
public IBM(string symbol, double price) : base(symbol, price) { }
}
class Program
{
static void Main(string[] args)
{
IBM ibm = new IBM("IBM", 150.00);
ibm.Attach(new Investor("aaa"));
ibm.Attach(new Investor("bbb"));
//Fluctuating prices will notify investors
ibm.Price = 150.00;
ibm.Price = 152.00;
ibm.Price = 130.00;
Console.ReadKey();
}
}
interface IInvestor
{
void Update(Stock stock);
}
class Investor : IInvestor
{
private string _name;
private Stock _stock;
public Investor(string name)
{
_name = name;
}
public void Update(Stock stock)
{
Console.WriteLine("Notified {0} of {1} 's change to {2:c}", _name, stock.Symbol, stock.Price);
}
public Stock Stock
{
get { return _stock; }
set { _stock = value; }
}
}
abstract class Stock
{
private string _symbol;
private double _price;
private List<IInvestor> _investors = new List<IInvestor>();
public Stock(string symbol, double price)
{
this._symbol = symbol;
this._price = price;
}
public void Attach(IInvestor investor)
{
_investors.Add(investor);
}
public void Detach(IInvestor investor)
{
_investors.Remove(investor);
}
public void Notify()
{
foreach (IInvestor investor in _investors)
{
investor.Update(this);
}
}
public double Price
{
get { return _price; }
set
{
if (_price != value)
{
_price = value;
Notify();
}
}
}
public string Symbol
{
get { return _symbol; }
}
}
class IBM : Stock
{
public IBM(string symbol, double price) : base(symbol, price) { }
}
No comments:
Post a Comment