Home  >  Article  >  Java  >  Briefly introduce how to use java to implement event-driven mechanism

Briefly introduce how to use java to implement event-driven mechanism

巴扎黑
巴扎黑Original
2017-09-05 11:56:261699browse

This article mainly introduces the implementation of event-driven mechanism using Java. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor to take a look

Due to project requirements, it is necessary to provide a class library for Java that supports event-driven mechanisms, which can implement event and delegate mechanisms similar to C#. As we all know, the Java language itself and its standard library do not provide relevant interfaces for event-driven mechanisms, although there are related classes in Swing (I don’t think it belongs to the standard library, because generally no one uses it:) to support this mechanism to implement components. Event processing, but it is coupled with the GUI after all, and it seems a bit awkward to use in other types of applications and lacks versatility. Therefore, it is necessary to implement a universal Java event-driven mechanism class library and then apply it to universal Java applications, although this is not difficult:)

Let us first examine the event driver of C# How to write a mechanism. The event keyword provided in C# can be easily used to define an event, and then by adding an event processing function to the event (in C#, a delegate is generally used to reference a function), and the relevant processing can be called when the event is triggered. Functions are event-driven processes. For example:


//定义事件和对应的委托
public event MyDelegate Click;
public delegate void MyDelegate();

//定义委托
void OnClick(){
  console.writeline("you just clicked me!");
}

//将委托与事件关联
Click += OnClick;

//触发事件
Click();

The above code is a simple example of the event-driven mechanism implemented in C#. It can be seen that it is very simple. This all stems from the language level of C# ( In fact, it is the convenience provided by CLR). Unfortunately, Java does not provide such convenience and requires humans to implement it. The following article will provide two methods for implementing event-driven mechanisms, for reference only.

Observer Pattern

The Observer pattern is a commonly used design pattern. The Observer first subscribes to the observed object (Subject). In this way, once a certain change occurs in the subject (Subject), the change will be notified to the observer (Observer).

This design pattern can be used in the event-driven mechanism. The event is equivalent to the observed object (Subject). Once the event is triggered, the event processing function will be called. The visible event processing function (in C# The delegate) can be thought of as an observer. Therefore, the above functions can be implemented as follows.


/*事件类*/
public Event {
  //与事件相关的事件处理函数
  public ArrayList<Callback> callbackList;
  
  //事件触发函数
  public void emit(){
    for(Callback cb : callbackList){
      cb.run();
    }
  }
  
  //注册事件处理函数
  public registerCallback(Callback cb){
    callbackList.add(cb);
  }
}

/*事件处理函数类*/
public interface Callback {
  void run();
}

public OnClick implements Callback {
  //函数
  public void run(){
    System.out.println("you just clicked me!");
  }
  
  
/*实现事件驱动*/
Event e = new Event(); 
//将OnClick事件处理函数注册到事件中
e.registerCallback(new OnClick()); 
//触发事件
e.emit();

The above Java code implements a simple event-driven mechanism. The principle is very simple and it is a typical application case of the observer pattern.

Using reflection

The Java language provides a powerful reflection function, which can obtain various components of a class at runtime (such as class name, class member functions, class attributes, etc.) and operate on them. Reflection is used below to implement a simple event-driven mechanism.


/*事件处理类*/
public class EventHandler {
  //事件源
  private Object sender;
  //事件处理函数名称(用于反射)
  private String callback;
  
  public EventHandler(Object sender, String callback){
    this.sender = sender;
    this.callback = callback;
  }
  
  //事件触发
  public void emit(){
  Class senderType = this.sender.getClass();
  try {
    //获取并调用事件源sender的事件处理函数
    Method method = senderType.getMethod(this.callback);
    method.invoke(this.sender);
    } catch (Exception e2) {
      e2.printStackTrace();
    }
  }
}


/*事件源*/
public class Button(){
  /*可以在此设置Button类的相关属性,比如名字等*/
  private String name;
  ...
  
  
  //事件处理函数
  public void onClick(){
    System.out.println("you just clicked me!");
  }
}
  
  
/*实现事件驱动机制*/
Button b = new Button();
if(/*收到按钮点击信号*/){
  EventHandler e = new EventHandler(b, "onClick");
  e.emit();
}

The above code shows the event-driven mechanism implemented using reflection. The advantage of using the reflection mechanism is that it has strong scalability. For example, it can be introduced into my event processing function A formal parameter of EventArgs, so that the event itself can have parameters, so that the event can carry more information. The rewritten event processing function is as shown in the following code:


public class EventArgs {
  //参数
  String p1;
  Integer p2;
  ...
  
}

//onClick事件处理函数改写
public void onClick(Object sender, EventArgs e){
  //参数e提供更多的信息
  System.out.println("Hello, you clicked me! " + e.p1 + e.p2);
}

//触发函数emit改写
public void emit(EventArgs e){
Class senderType = this.sender.getClass();
try {
  //获取并调用事件源sender的事件处理函数
  Method method = senderType.getMethod(this.callback, this.getClass(), e.getClass());
  method.invoke(this.sender, this.sender, e);
  } catch (Exception e2) {
    e2.printStackTrace();
  }
}

Does it sound familiar? That's right, the event handling function (onClick function in the code) automatically generated by Visual studio for you when writing a Winform form in C# has almost the same form, but this time we implement it in Java.

Of course, in addition to the two methods mentioned above that can implement Java's event-driven mechanism, there are other methods, such as using Java's internal classes. The author has also written some sample codes. , I won’t go into details here, I’ll leave it to you later.

The above is the detailed content of Briefly introduce how to use java to implement event-driven mechanism. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn