Events are objects or messages used when a software components wants to notify a state change to other components.
An Event model is a software architecture (a set of classes and interfaces) that determine how components can:
1. On the event source side:
1. create and describe events
2. trigger (or fire) events
3. distribute events to interested components
2. On the event listener side:
1. subscribe to event sources
2. react to events when received
3. remove the subscription to event sources when desired
Terminology often used refers to:
1. Event Source or Provider: the sender of events
2. Event: the object sent
3. Event Listener or Event Sink or Consumer: the receiver of events.
The Java Event Model: Example 1
The following code illustrates how to implement the simplest application of the Java event model:
--------------------------------------------------------------------------------
// Define a new event
public class StockPriceChangeEvent extends EventObject {
private long newPrice;
public StockPriceChangeEvent(Object source, long np) {
super(source);
newPrice = np;
}
public long getNewPrice() {
return newPrice;
}
// Type-safe access to source
public Stock getStock() {
return (Stock)getSource();
}
}
// Define new listener interface
public interface StockListener extends EventListener {
public abstract void onStockPriceChange(StockPriceChangeEvent e);
}
// Define a source for the event
public class Stock {
private long currentPrice;
private Vector stockListeners = new Vector();
private String name;
public Stock(String n) {name = n;}
public setPrice(long np) {
currentprice = np;
notifyStockPriceChange();
}
public synchronized void addStockListener(StockListener l) {
stockListeners.addElement(l);
}
public synchronized void removeStockListener(StockListener l) {
stockListeners.removeElement(l);
}
protected void notifyStockPriceChange() {
StockPriceChangeEvent e = new StockPriceChangeEvent(this, currentPrice);
for (int i = 0; i < stockListeners.size(); i++ ) {
StockListener l = (StockListener)stockListeners.elementAt(i);
l.onStockPriceChange(e);
}
}
}
// Define a listener for the event
public class Trader implements StockListener {
public Trader() {
ibm = new Stock("ibm");
ibm.addStockListener(this);
}
...
public onStockPriceChange(StockPriceChangeEvent e) {
if (e.getNewPrice() > 103) {
Buy(e.getStock());
}
}
}