using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace DesignFactory.Observer
{
/// <summary>
/// 观察者模式
/// </summary>
class Observerpattern
{
}
abstract class Stock
{
protected string symbol;
protected double price;
private ArrayList investors = new ArrayList();
public Stock(string symbol, double price)
{
this.symbol = symbol;
this.price = price;
}
public void Attach(Investor investor)
{
investors.Add(investor);
}
public void Detach(Investor investor)
{
investors.Remove(investor);
}
public void Notify()
{
foreach (Investor i in investors)
{
i.Update(this);
}
}
public double Price
{
get { return price; }
set
{
price = value;
Notify();
}
}
public string Symbol
{
get { return symbol; }
set { symbol = value; }
}
}
class IBM : Stock
{
public IBM(string symbol, double price) : base(symbol, price) { }
}
interface IInvestor
{
void Update(Stock stock);
}
class Investor : IInvestor
{
private string name;
private string observerState;
private Stock stock;
public Investor(string name)
{
this.name = name;
}
public void Update(Stock stock)
{
Console.WriteLine("Notified investor {0} of {1}'s change to {2:C}", name, stock.Symbol, stock.Price);
}
public Stock Stock
{
get { return stock; }
set { stock = value; }
}
}
public class ObserverApp
{
public static void Main(string[] args)
{
Investor s = new Investor("Sorros");
Investor b = new Investor("Berkshire");
IBM ibm = new IBM("IBM", 120.00);
ibm.Attach(s);
ibm.Attach(b);
ibm.Price = 120.10;
ibm.Price = 121.00;
ibm.Price = 120.50;
ibm.Price = 120.75;
}
}
}
【设计模式】之 Observer 观察者模式
最新推荐文章于 2025-06-11 23:07:24 发布