zoukankan      html  css  js  c++  java
  • .net中的观察者模式(用delegate/event实现)

    using System;

    namespace ConsoleApplication1
    {


        
    //用户界面(观察者1)
        public class SomeKindOfUI
        
    {
            
    public void Show(object anObject)
            
    {
                
    if (anObject is SomeData)
                
    {
                    ImpShow((SomeData)anObject);
                }

            }


            
    public void ImpShow(SomeData data)
            
    {
                Console.WriteLine(
    "Observe1. The new ask price is: " + data.AskPrice);
            }

        }


        
    //用户界面(观察者2)
        public class AnotherKindOfUI
        
    {
            
    public void Show(object anObject)
            
    {
                
    if (anObject is SomeData)
                
    {
                    ImpShow((SomeData)anObject);
                }

            }


            
    public void ImpShow(SomeData data)
            
    {
                Console.WriteLine(
    "Observe2. The new ask price is: " + data.AskPrice);
            }

        }



        
    //业务数据(被观察对象)
        public class SomeData 
        
    {

            
    public delegate void UpdateHandler(object sender);
            
    public event UpdateHandler UpdateEvent;

            
    //被观察者中的数据
            float _askPrice;

            
    //改变数据的属性
            public float AskPrice 
            
    {
                
    set 
                
    {
                    _askPrice 
    = value;
                    
    if (UpdateEvent != null)
                        UpdateEvent(
    this);
                }

                
    get
                
    {
                    
    return _askPrice;
                }

            }

        }
     


        
    /// <summary>
        
    /// Summary description for Class1.
        
    /// </summary>

        class Class1
        
    {
            
    /// <summary>
            
    /// The main entry point for the application.
            
    /// </summary>

            [STAThread]
            
    static void Main(string[] args)
            
    {
                SomeKindOfUI ui 
    = new SomeKindOfUI();
                AnotherKindOfUI anoth 
    = new AnotherKindOfUI();
                SomeData data 
    = new SomeData();
                data.UpdateEvent 
    += new SomeData.UpdateHandler(ui.Show);//observer1
                data.UpdateEvent += new SomeData.UpdateHandler(anoth.Show);//observer2
                data.AskPrice = 6789.2f;
            }

        }

    }

  • 相关阅读:
    Feature fake , new view in comment.
    MeeGo Architect
    小米手机 怪诞行为经济学
    [转载]ten years as a programmer
    C++ 头文件
    关于AGILE/TDD 和传统的design
    你是否在开发正确的产品
    正确的创业
    MeeGo架构
    Unit Test
  • 原文地址:https://www.cnblogs.com/silva/p/266502.html
Copyright © 2011-2022 走看看