• .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;
            }

        }

    }

  • 相关阅读:
    dockerfile 踩坑记录
    Windows安装配置xampp
    docker 容器中设置 mysql lampp php软链接
    linux 软件连接 创建/查看/删除
    mysql 远程连接权限
    linux设置静态获取ip
    android 自定义控件中获取属性的三种方式(转)
    android 自定义组件-带图片的textView
    CodeIgniter 3之Session类库(3)(转)
    CodeIgniter 3之Session类库(2)(转)
  • 原文地址:https://www.cnblogs.com/silva/p/266502.html
Copyright © 2020-2023  润新知