用Java创build一个自定义事件

我想在Java中这样做,但我不知道的方式:

当事件“对象1说'你好'”发生,则对象2通过说“你好”来响应该事件。

有人可以给我一个提示或示例代码?

你可能想看看观察者模式 。

下面是一些示例代码,让你开始:

import java.util.*; // An interface to be implemented by everyone interested in "Hello" events interface HelloListener { void someoneSaidHello(); } // Someone who says "Hello" class Initiater { private List<HelloListener> listeners = new ArrayList<HelloListener>(); public void addListener(HelloListener toAdd) { listeners.add(toAdd); } public void sayHello() { System.out.println("Hello!!"); // Notify everybody that may be interested. for (HelloListener hl : listeners) hl.someoneSaidHello(); } } // Someone interested in "Hello" events class Responder implements HelloListener { @Override public void someoneSaidHello() { System.out.println("Hello there..."); } } class Test { public static void main(String[] args) { Initiater initiater = new Initiater(); Responder responder = new Responder(); initiater.addListener(responder); initiater.sayHello(); // Prints "Hello!!!" and "Hello there..." } } 

相关文章: Java:创build自定义事件

你想要的是观察者模式的实现。 你可以完全自己做,或者使用java.util.Observerjava.util.Observable类的java类

有三种不同的方法可以设置:

  1. Thrower里面的Thrower
  2. CatcherThrower里面
  3. 在这个例子中的另一个类中的ThrowerCatcher Test

工作Github示例我是CITING默认为选项3,尝试其他人只需取消注释要作为主类的“ Optional ”代码块,并将该类设置为build.xml${Main-Class}variablesbuild.xml文件:

4需要抛出代码的东西:

 import java.util.*;//import of java.util.event //Declaration of the event's interface type, OR import of the interface, //OR declared somewhere else in the package interface ThrowListener { public void Catch(); } /*_____________________________________________________________*/class Thrower { //list of catchers & corresponding function to add/remove them in the list List<ThrowListener> listeners = new ArrayList<ThrowListener>(); public void addThrowListener(ThrowListener toAdd){ listeners.add(toAdd); } //Set of functions that Throw Events. public void Throw(){ for (ThrowListener hl : listeners) hl.Catch(); System.out.println("Something thrown"); } ////Optional: 2 things to send events to a class that is a member of the current class . . . go to github link to see this code . . . } 

2类文件需要从类中接收事件

 /*_______________________________________________________________*/class Catcher implements ThrowListener {//implement added to class //Set of @Override functions that Catch Events @Override public void Catch() { System.out.println("I caught something!!"); } ////Optional: 2 things to receive events from a class that is a member of the current class . . . go to github link to see this code . . . }