gpt4 book ai didi

java - Java中的事件通知

转载 作者:行者123 更新时间:2023-11-30 05:08:07 24 4
gpt4 key购买 nike

在java中,我对观察者模式或JMS感到非常困惑。我想使用如下所示的事件通知。 让我们忘记那些JMS或Observer,你认为这是可能的还是可行的?如果是,如何完成?

newSalesOrder = new SalesOrder();
newSalesOrder.notified("new SalesOrder order ID="+orderId);

EventRegister.bindEvent(SalesOrder.class, Delivery.class);
EventRegister.bindEvent(SalesOrder.class, Warehouse.class);

////////////
Delivery delivery = new Delivery();
delivery.listerning(new Event(source){
if(source == SalesOrder.class){

}
});

//////////
Warehouse warehouse = new Warehouse();
warehouse.listerning(new Event(source){
if(source == SalesOrder.class){

}
});

///////////
EventRegister{
static bindEvent(Class source, Class destination){
//???
}
}

最佳答案

您需要注册(绑定(bind))对象而不是类。您可以在 EventRegister 中保持注册列表静态,但我认为最好将它们保留为 SalesOrder 中的实例。所以它会是:

import java.util.ArrayList;
import java.util.List;

public class Test {
public static void main(String[] args) {
SalesOrder mySalesOrder = new SalesOrder();

Warehouse myWarehouse = new Warehouse();
mySalesOrder.addListener(myWarehouse);

Delivery myDelivery = new Delivery();
mySalesOrder.addListener(myDelivery);

Event myEvent = new Event();
// Now 'myDelivery' and 'myWarehouse' objects will receive 'myEvent'
// object on their 'onEvent(Event event)' method
System.out.println("Event to be published: " + myEvent);
mySalesOrder.publishEvent(myEvent);
}
}

interface Listener {
public void onEvent(Event event);
}

class Event {
// Add reqired detail here!
}

class SalesOrder {
private List<Listener> listeners = new ArrayList<Listener>();

public void addListener(Listener listener) {
listeners.add(listener);
}

public void removeListener(Listener listener) {
listeners.remove(listener);
}

// Use proper access modifier
public void publishEvent(Event event) {
System.out.println(this + " is goint to publish " + event
+ " to " + listeners + " listeners.");
for (Listener listener : listeners) {
listener.onEvent(event);
}
}

// ...
}

class Warehouse implements Listener {
public void onEvent(Event event) {
// Do something when event received
System.out.println(event + " received at " + this);
}
// ...
}

class Delivery implements Listener {
public void onEvent(Event event) {
// Do something when event received
System.out.println(event + " received at " + this);
}
// ...
}

如果你运行它,它会打印如下内容:

Event to be published: Event@190d11

SalesOrder@a90653 is goint to publish Event@190d11 to [Warehouse@de6ced, Delivery@c17164] listeners.

Event@190d11 received at Warehouse@de6ced

Event@190d11 received at Delivery@c17164

这是一个简单的示例,在现实生活中的用例中,您可以考虑使用线程安全实现,并使用组合或继承从 SalesOrder 中重构注册。

关于java - Java中的事件通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4379623/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com