请举一个IntelliJ IDEA 发布订阅 信息输入的例子 用java代码
时间: 2024-02-25 18:52:10 浏览: 75
好的,下面是一个简单的 IntelliJ IDEA 发布订阅信息输入的例子:
首先,我们需要定义一个事件类,用于发布和订阅事件:
```java
import java.util.EventObject;
public class MyEvent extends EventObject {
private final String message;
public MyEvent(Object source, String message) {
super(source);
this.message = message;
}
public String getMessage() {
return message;
}
}
```
接下来,我们需要定义一个发布者类,它负责发布事件:
```java
import java.util.ArrayList;
import java.util.List;
public class MyPublisher {
private final List<MyEventListener> listeners = new ArrayList<>();
public void addListener(MyEventListener listener) {
listeners.add(listener);
}
public void removeListener(MyEventListener listener) {
listeners.remove(listener);
}
public void publishEvent(String message) {
MyEvent event = new MyEvent(this, message);
for (MyEventListener listener : listeners) {
listener.handleEvent(event);
}
}
}
```
然后,我们需要定义一个订阅者接口和一个实现订阅者接口的类:
```java
import java.util.EventListener;
public interface MyEventListener extends EventListener {
void handleEvent(MyEvent event);
}
public class MySubscriber implements MyEventListener {
@Override
public void handleEvent(MyEvent event) {
System.out.println("Received message: " + event.getMessage());
}
}
```
最后,我们可以使用上面的类来发布和订阅事件:
```java
public class Main {
public static void main(String[] args) {
MyPublisher publisher = new MyPublisher();
MySubscriber subscriber = new MySubscriber();
publisher.addListener(subscriber);
publisher.publishEvent("Hello, world!");
publisher.removeListener(subscriber);
}
}
```
输出结果为:
```
Received message: Hello, world!
```
以上就是一个简单的 IntelliJ IDEA 发布订阅信息输入的例子。
阅读全文