你可能想调查一下观测器模式.
下面是一些让自己开始工作的示例代码:import java.util.*;// An interface to be implemented by everyone interested in "Hello" eventsinterface HelloListener {
void someoneSaidHello();}// Someone who says "Hello"class Initiater {
private List listeners = new ArrayList();
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" eventsclass 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..."
}}