zoukankan      html  css  js  c++  java
  • 行为型-观察者模式、基于事件的观察者

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    //行为型-观察者模式、基于事件的观察者
    namespace Chap2_2
    {
    public class Observer
    {
    Employee emp = EmployeeFactory.CreateEmployee("Alfred_Xu", "南京、成都", EmployeeFactory.addressFactory);
    public void testObserver()
    {
    emp.EmployeeChangenameEvent += Employee.employee_EmployeeChangeNameEvent;//订阅事件,定义事件触发后,由谁来做什么
    emp.ChangeName("Alfred.Xu");
    Console.ReadKey();
    }

    public void testObserver2()
    {

    emp.EmployeeChangenameEvent += empChangeName;//订阅事件
    emp.ChangeName("Alfred.Xu");
    Console.ReadKey();
    }

    public void empChangeName(string name)
    {
    Console.WriteLine("修改后的名称;" + name);
    }
    public void show()
    {
    Console.WriteLine(string.Format("员工名:{0}", emp.Name));
    Console.WriteLine(string.Format("户籍地:{0}", emp.AddressCollection.Address1));
    Console.WriteLine(string.Format("工作地:{0}", emp.AddressCollection.Address2));
    }
    }

    public partial class Employee
    {
    //定义委托
    public delegate void EmployeeChangedName(string ChangedName);
    //创建委托对象
    private EmployeeChangedName employeeChangedName;
    //具体的事件
    public event EmployeeChangedName EmployeeChangenameEvent
    {
    add { employeeChangedName += value; }
    remove { if (employeeChangedName != null) { employeeChangedName -= value; } }
    }
    //该方法执行时,触发事件
    public void ChangeName(string name)
    {
    this.Name = name;
    this.employeeChangedName(name);//事件只有在对象内部才能触发
    }
    //事件的具体执行,方法与上面的委托一致
    static public void employee_EmployeeChangeNameEvent(string ChangeName)
    {
    Console.WriteLine("修改后的名称;"+ChangeName);
    }
    }
    }

  • 相关阅读:
    Android studio ButterKnife插件
    Android Studio Prettify 插件
    Android studio的主题颜色修改
    MeasureSpec 的三中类型
    android 加载远程Jar、APK
    android源码 键盘消息处理机制
    Android源码阅读笔记二 消息处理机制
    phpstrom 激活
    sublime vue 语法高亮插件安装
    mysql登录报错“Access denied for user 'root'@'localhost' (using password: YES”的处理方法
  • 原文地址:https://www.cnblogs.com/sulong/p/4917990.html
Copyright © 2011-2022 走看看