event notification in Java
In java, I f开发者_C百科eed very confused on observer pattern or JMS. I want to use the event notification like below. Let us forget about those JMS or Observer, do you think it is possible or doable ? if yes, how to complete it ?
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){
//???
}
}
You need to register (bind) objects not classes. You can keep registration list static at EventRegister but I think it's better to keep them as instance at SalesOrder. So it would be:
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);
}
// ...
}
If you run it it will print something like:
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
This is a trivial sample, in real life use cases you may consider using a thread-safe implementation and refactoring registration out of SalesOrder using composition or inheritance.
精彩评论