四.观察者实例分析(Example

1、场景

假设有一股票开盘价格16.50元,自从上市以来价格是不断下降,而且以1.00元的速度下降。
在股票降到12.00元时,股民灵动生活买入了股票。
在股票降到8.05元时,股民Jane买了股票。

2、观察者实例结构

       Net设计模式之观察者模式(Observer Pattern)(2)
Stock,抽象通知者
定义了委托PriceChangedHandler ,调用了事件参数StockDetailsArgs 
声明了事件PriceChanged.
股票在下跌的过程中调用方法OnPriceChanged ,通过此方法触发事件PriceChanged 
AttachEvent 方法用来添加观察者到对象
StockDetailArgs,事件参数继承于EventArgs类,有树形CurrentPrice用来专递价格数据
接口IObserver和具体观察者Observer类:
Stoc_PriceChanged方法:当股票在以1.00元降价的过程中调用此方法。当价格降到符合购买者价格,而且股票没有被其他人购买的情况时,执行购买行为。
开盘价格:16.50
收盘价格:5.50
当价格降到12.00时,观察者灵动生活买入此股票
当价格降到8.05时,观察者Jane买入此股票
 

3、代码

1Stock股票类
public class Stock
{
    private double _openPrice;
    private double _closePrice;
    public delegate void PriceChangedHandler(object sender, StockDetailArgse);
    public event PriceChangedHandler PriceChanged;
 
    public double OpenPrice
    {
        get { return _openPrice; }
        set { _openPrice = value; }
    }
    public double ClosePrice
    {
        get { return _closePrice; }
        set { _closePrice = value; }
    }
 
    public void StartTrading()
    {
        double current;
 
        //Current price decrements by $1.00 as the stock is traded  
        current = OpenPrice;
 
        while (current > ClosePrice)
        {
            //Stock is falling in increments of $1.00  
            current = current - 1.00;
 
            //Call the method to raise the event  
            OnPriceChanged(current);
 
            //Simulate a delay of 2000ms between market price updates  
            System.Threading.Thread.Sleep(2000);
        }
    }
 
    protected void OnPriceChanged(double currentMarketPrice)
    {
        //Any handlers attached to this event?
        if (PriceChanged != null)
        {
            StockDetailArgs args = new StockDetailArgs();
            args.CurrentPrice = currentMarketPrice;
            Console.WriteLine("当前股票价格是:" + args.CurrentPrice.ToString());
            ////Raise the event
            PriceChanged(this, args);
        }
    }
 
    /// <summary>
    /// 添加观察者
    /// </summary>
    /// <param name="observer">观察者</param>
    public void AttachEvent(IObserver observer)
    {
        PriceChanged += new PriceChangedHandler(observer.Stoc_PriceChanged);
    }
}
 
2、事件参数StockDetailArgs
public class StockDetailArgsEventArgs
{
    private double _currentPrice;
 
    public double CurrentPrice
    {
        get { return _currentPrice; }
        set { _currentPrice = value; }
    }
}
 
 
3、观察者接口IObserver
public interface IObserver
{
    void Stoc_PriceChanged(object sender, StockDetailArgs e);
}
 
4、具体观察者Observer
public class Observer : IObserver
{
    private string _investorName;
    private double _buyPrice;
    private Stock _stoc;
    private bool _hasBoughtStock = false;
 
    public string InvestorName
    {
        get { return _investorName; }
        set { _investorName = value; }
    }
    public double BuyPrice
    {
        get { return _buyPrice; }
        set { _buyPrice = value; }
    }
    public Stock Stoc
    {
        get { return _stoc; }
        set { _stoc = value; }
    }
 
    public Observer(string investorName, double buyPrice)
    {
        this.InvestorName = investorName;
        this.BuyPrice = buyPrice;
    }
 
    public void Stoc_PriceChanged(object sender, StockDetailArgs e)
    {
        if (e.CurrentPrice <= BuyPrice && _hasBoughtStock == false)
        {
            Console.WriteLine(string.Format("{0}在价格Price ={1}时买进了股票。",InvestorName,e.CurrentPrice));
            _hasBoughtStock = true;
        }
    }
}
 
5、客户端代码
static void Main(string[] args)
{
    Stock stock = new Stock();
    stock.OpenPrice = 16.50;
    stock.ClosePrice = 5.50;
 
    Observer james = new Observer("灵动生活", 12.00);
    Observer jane = new Observer("jane",8.05);
    stock.AttachEvent(james);
    stock.AttachEvent(jane);
    stock.StartTrading();
    Console.Read();
}
 

4、程序运行结果

Net设计模式之观察者模式(Observer Pattern)(2)

五、总结(Summary

观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象,这个主题对象在状态发生变化的时,会通知所有观察者对象,使他们能够自动更新自己。解决的是“当一个对象的改变需要同时改变其他对象的时候”问题。









本文转自 灵动生活 51CTO博客,原文链接:http://blog.51cto.com/smartlife/258931,如需转载请自行联系原作者

相关文章:

  • 2021-04-11
  • 2021-04-13
  • 2021-06-24
猜你喜欢
  • 2022-01-09
  • 2021-10-02
  • 2021-05-14
  • 2021-09-30
  • 2021-08-05
  • 2021-10-10
相关资源
相似解决方案