Java中的事件通知

时间:2010-12-07 17:26:48

标签: java events

在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){
      //???
    }
}

1 个答案:

答案 0 :(得分:2)

您需要注册(绑定)对象而不是类。您可以在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 @ 190d11

     

SalesOrder @ a90653是goint将Event @ 190d11发布给[Warehouse @ de6ced,Delivery @ c17164]听众。

     

活动@ 190d11在Warehouse @ de6ced

收到      

活动@ 190d11收到Delivery @ c17164

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