Java的事件

目录

1. 事件机制

1.1. 核心语法

Java事件机制包括3个部分(角色、元素):事件、事件源和事件监听器。

我们如何使用事件:1)创建事件源对象,2)向事件源对象注册监听器,3)调用事件源对象的方法方法触发事件的生成并且调用监听器的回调方法处理事件

事件源:

当事件源状态发生变化时,触发(创建)事件(事件本身包含事件源的信息),并通知(广播)注册的监听器处理事件。

监听器

每一个事件类型,对应都需要定义一个回调方法(Java一般采用这种方法,且参数就是该事件类型,单参),或者一个监听器类型。

事件

1.2. 语法变种

事件除了必须给出事件源外,还可以定义自己的状态。

https://www.cnblogs.com/atyou/archive/2013/01/07/2850321.html

1.3. 观察者设计模式的应用

见设计模式-观察者模式一节,可知事件机制就是它的一个应用。

Define a one-to-many dependency between objects so that when one object(主题) changes state, all its dependents(观察者) are notified and updated automatically.

using System;

using System.Collections.Generic;

namespace DoFactory.GangOfFour.Observer.RealWorld

{

  class MainApp

  {

    static void Main()

    {

      IBM ibm = new IBM("IBM", 120.00);

      ibm.Attach(new Investor("Sorros"));

      ibm.Attach(new Investor("Berkshire"));

      ibm.Price = 120.10;

      ibm.Price = 121.00;

      ibm.Price = 120.50;

      ibm.Price = 120.75;

      Console.ReadKey();

    }

  }

abstract class Stock

  {

    private string _symbol;

    private double _price;

private List<IInvestor> _investors = new List<IInvestor>();

    public Stock(string symbol, double price)

    {

      this._symbol = symbol;

      this._price = price;

    }

    public void Attach(IInvestor investor)

    {

      _investors.Add(investor);

    }

    public void Detach(IInvestor investor)

    {

      _investors.Remove(investor);

    }

    public void Notify()

    {

      foreach (IInvestor investor in _investors)

      {

        investor.Update(this);

      }

      Console.WriteLine("");

    }

    public double Price

    {

      get { return _price; }

      set

      {

        if (_price != value)

        {

          _price = value;

          Notify();

        }

      }

    }

    public string Symbol

    {

      get { return _symbol; }

    }

  }

  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 Stock _stock;

    public Investor(string name)

    {

      this._name = name;

    }

    public void Update(Stock stock)

    {

      Console.WriteLine("Notified {0} of {1}'s " +

        "change to {2:C}", _name, stock.Symbol, stock.Price);

    }

    public Stock Stock

    {

      get { return _stock; }

      set { _stock = value; }

    }

  }

}

1.4. 参考资料

https://www.cnblogs.com/atyou/archive/2013/01/07/2850321.html

https://www.dofactory.com/net/design-patterns

猜你喜欢

转载自www.cnblogs.com/zhizaixingzou/p/10068335.html