internet software development the java event model lecture 5

31
Internet Software Internet Software Development Development The Java Event Model The Java Event Model Lecture 5 Lecture 5

Upload: jeffrey-benson

Post on 23-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Internet Software Internet Software DevelopmentDevelopment

The Java Event ModelThe Java Event Model

Lecture 5Lecture 5

The Java Event ModelThe Java Event Model

ContentsContents Introduction to EventsIntroduction to Events The Java Event modelThe Java Event model Using this model to notify Customers that Using this model to notify Customers that

Pizzas are ready from a BakeryPizzas are ready from a Bakery This example is taken from This example is taken from JavaBeans by JavaBeans by

ExampleExample, by Henri Jubin, Prentice Hall, by Henri Jubin, Prentice Hall

Pauls Pictures Pauls Documents Pauls Sums Pauls Homework

ProblemsProblems

Pauls Pictures Pauls Documents Pauls Sums Pauls Homework Pauls ToDo Lists

My DocumentsReportsPapersPresentations

Client

Window LibraryWindow Library

File SystemCalls

But I need totell you

something!

Slide Shows

I’m in chargehere, guys!

EventsEvents

An abstraction of Callback that is An abstraction of Callback that is applicable to “federations” of interacting applicable to “federations” of interacting componentscomponents

The firing of an event is a way of one The firing of an event is a way of one object telling one or more other recipients object telling one or more other recipients that something interesting has happenedthat something interesting has happened The sender The sender firesfires an event an event A recipient is called a A recipient is called a listenerlistener and and handleshandles the the

eventevent

The Java Event ModelThe Java Event Model

ContentsContents Introduction to EventsIntroduction to Events The Java Event modelThe Java Event model Using this model to notify Customers that Using this model to notify Customers that

Pizzas are ready from a BakeryPizzas are ready from a Bakery This example is taken from This example is taken from JavaBeans by JavaBeans by

ExampleExample, by Henri Jubin, Prentice Hall, by Henri Jubin, Prentice Hall

Java Event ModelJava Event Model

Event SourceEvent Source

Event ListenerEvent Listener

Register Event Listener

Fire Event

EventObject

EventObject

Event ObjectsEvent Objects

Encapsulates information specific to an Encapsulates information specific to an instance of an eventinstance of an event

E.g. a “mouse click” event may contain:E.g. a “mouse click” event may contain: The position of the mouse pointerThe position of the mouse pointer Which mouse button was clicked (and how Which mouse button was clicked (and how

many times)many times) The event object is passed as a parameter The event object is passed as a parameter

to the event notification methodto the event notification method

Event ListenersEvent Listeners

These are objects that need to be notified These are objects that need to be notified when a certain event occurswhen a certain event occurs

Event notifications are made through Event notifications are made through method invocations in the listening objectmethod invocations in the listening object The event object is passed as a parameterThe event object is passed as a parameter The event source must know which listener The event source must know which listener

object(s) to callobject(s) to call This information is contained in an event-This information is contained in an event-

listener interfacelistener interface

Event SourcesEvent Sources

Objects that fire eventsObjects that fire events Implement methods that allow listeners to:Implement methods that allow listeners to:

Register their interest in the events they Register their interest in the events they generate;generate;

Unregister their interest in the events they Unregister their interest in the events they generate.generate.

Multicast event deliveryMulticast event delivery enables an event enables an event to be fired to a number of event-listenersto be fired to a number of event-listeners

SummarySummary

EventObject

source

getSource()toString()

EventListener

notification(evt)

EventSource

addListener()removeListener()

fires passed to

registers 0..*

invokes notifications in 0..*

The Java Event ModelThe Java Event Model

ContentsContents Introduction to EventsIntroduction to Events The Java Event modelThe Java Event model Using this model to notify Customers that Using this model to notify Customers that

Pizzas are ready from a BakeryPizzas are ready from a Bakery This example is taken from This example is taken from JavaBeans by JavaBeans by

ExampleExample, by Henri Jubin, Prentice Hall, by Henri Jubin, Prentice Hall

Java Event ModelJava Event Model

Event SourceEvent Source

Event ListenerEvent Listener

Register Event Listener

Fire Event

EventObject

EventObject

Chili PizzaExpressChili PizzaExpressEventObject

source

getSource()toString()

Bakery

addOrderListener()removeOrderListener()sendMessage(PizzaEvent)

fires passed to

registers with 0..*

invokes notifications in 0..*

«interface»OrderListener

pizzaStatus(evt)

Customer

run( )

iNumberiSliceNumber

PizzaEvent

PizzaEvent.javaPizzaEvent.java

import java.util.EventObject;import java.util.EventObject;

public class PizzaEvent extends public class PizzaEvent extends EventObject {EventObject {

public PizzaEvent(Object aSource) {public PizzaEvent(Object aSource) {

super(aSource);super(aSource);

}}

}}

EventObject

source

getSource()toString()

PizzaEvent

OrderListener.javaOrderListener.java

import java.util.EventListener;import java.util.EventListener;

public interface OrderListener extends public interface OrderListener extends

EventListener {EventListener {

public void pizzaStatus(PizzaEvent anEvent);public void pizzaStatus(PizzaEvent anEvent);

}}

EventListener

OrderListener

pizzaStatus

Bakery.javaBakery.javapublic class Bakerypublic class Bakery

public Bakery( ) {public Bakery( ) { // constructor of a Bakery instance// constructor of a Bakery instance }} public addOrderListener( eL ) {public addOrderListener( eL ) {

// inserts OrderListeners in some // inserts OrderListeners in some // structure// structure

}} public removeOrderListener( eL ) {public removeOrderListener( eL ) {

// deletes OrderListeners from that// deletes OrderListeners from that// structure// structure

}} private void sendMessage( evt ) {private void sendMessage( evt ) {

// broadcast evt somehow// broadcast evt somehow }}

Bakery

addOrderListenerremoveOrderListenersendMessage(PizzaEvent)

Properties of Bakery.javaProperties of Bakery.java

import java.lang.Thread;import java.lang.Thread;import java.util.*;import java.util.*;

public class Bakery implements Runnable {public class Bakery implements Runnable {private Vector iCustomers = new Vector( );private Vector iCustomers = new Vector( );private Thread iThread;private Thread iThread;

// methods go here…// methods go here…

}}

Constructor for BakeryConstructor for Bakery

public Bakery ( ) {public Bakery ( ) {

iThread = new Thread(this);iThread = new Thread(this);

iThread.start( );iThread.start( );

}}

// When a new instance of Bakery is created,// When a new instance of Bakery is created,

// a flow of control owned by it is started.// a flow of control owned by it is started.

The main flow of controlThe main flow of control

public void run( ) {public void run( ) {

while(true) {while(true) {

iThread.sleep(4000);iThread.sleep(4000);

PizzaEvent event = new PizzaEvent(this);PizzaEvent event = new PizzaEvent(this);

sendMessage(event);sendMessage(event);

}}

}}

// a Bakery broadcasts a message that Pizza is ready// a Bakery broadcasts a message that Pizza is ready

// every 4 seconds// every 4 seconds

Adding and removing Adding and removing ListenersListeners

public void addOrderListener(OrderListener aListener) {public void addOrderListener(OrderListener aListener) {

iCustomers.addElement(aListener);iCustomers.addElement(aListener);

}}

// Remember iCustomers is a Vector field in Bakery// Remember iCustomers is a Vector field in Bakery

public void removeOrderListener(OrderListener aListener) {public void removeOrderListener(OrderListener aListener) {

iCustomers.removeElement(aListener);iCustomers.removeElement(aListener);

}}

Broadcasting the messageBroadcasting the message

private void sendMessage(PizzaEvent anEvent) {private void sendMessage(PizzaEvent anEvent) {

Vector v;Vector v;

v = iCustomers.clone( );v = iCustomers.clone( );

for (int i = 0; i<v.size( ); i++) {for (int i = 0; i<v.size( ); i++) {

OrderListener ol = v.elementAt(i);OrderListener ol = v.elementAt(i);

ol.pizzaStatus(anEvent); ol.pizzaStatus(anEvent); // implement in Customer// implement in Customer

}}

System.out.println(“Pizza ready …”);System.out.println(“Pizza ready …”);

}}

Summary for SourcesSummary for Sources

Record all the references to Listener Record all the references to Listener Objects in a “Vector”Objects in a “Vector”

Register Listeners by adding their name to Register Listeners by adding their name to the Vectorthe Vector

Unregister Listeners by removing their Unregister Listeners by removing their name from the Vectorname from the Vector

Step through the elements of the Vector to Step through the elements of the Vector to notify all the Listenersnotify all the Listeners

The Story so FarThe Story so FarEventObject

source

getSource()toString()

Bakery

addOrderListener()removeOrderListener()sendMessage(PizzaEvent)

fires passed to

registers with 0..*

invokes notifications in 0..*

«interface»OrderListener

pizzaStatus(evt)

Customer

run( )

iNumberiSliceNumber

PizzaEvent

The Customer ClassThe Customer Class

A Customer also has its own flow of controlA Customer also has its own flow of controlpublic class Customer implements OrderListener,public class Customer implements OrderListener,

Runnable {Runnable {private int iNumber; private int iNumber; // identify customer// identify customerprivate boolean iHaveSlice; private boolean iHaveSlice; // something to eat?// something to eat?private Thread iThread;private Thread iThread; // identifiy flow of control// identifiy flow of controlprivate Randon iRandom;private Randon iRandom; // gaps between bites// gaps between bitesprivate int iSliceNumber;private int iSliceNumber; // Slices eaten// Slices eaten

… … }}

Construct a CustomerConstruct a Customer

public Customer(int aNumber) {public Customer(int aNumber) {

iNumber = aNumber;iNumber = aNumber;

iRandom = new Random(aNumber);iRandom = new Random(aNumber);

iThread = new Thread(this);iThread = new Thread(this);

iThread.start( );iThread.start( );

}}

// Construct a Customer with a specified identifier, and// Construct a Customer with a specified identifier, and

// start its own flow of control// start its own flow of control

Making your Customer RunMaking your Customer Runpublic void run( ) {public void run( ) {

while(true) {while(true) {if (iHaveSlice) {if (iHaveSlice) {

for (int bites=0; bites<4; bites++) {for (int bites=0; bites<4; bites++) {System.out.println(“customer: “ + iNumber +System.out.println(“customer: “ + iNumber +bites + “ slice:” + iSliceNumber);bites + “ slice:” + iSliceNumber);iThread.sleep(iRandom.nextFloat( ) * 3000);iThread.sleep(iRandom.nextFloat( ) * 3000);}}iHaveSlice = false;iHaveSlice = false;iThread.suspend( );iThread.suspend( );

}}}} // Takes 4 bites, with a rest between each, then// Takes 4 bites, with a rest between each, then

}} // waits for some more Pizza.// waits for some more Pizza.

Response to PizzaEventsResponse to PizzaEvents

Remember, we invoked a method called Remember, we invoked a method called “pizzaStatus” when we broadcast “pizzaStatus” when we broadcast messages from the Bakery. Customer messages from the Bakery. Customer must implement this:must implement this:

public void pizzaStatus(PizzaEvent anEvent) {public void pizzaStatus(PizzaEvent anEvent) {if ( ! iHaveSlice) {if ( ! iHaveSlice) {iHaveSlice = true;iHaveSlice = true;iSliceNumber++;iSliceNumber++;iThread.resume( );iThread.resume( );

}}

WarningWarning

These slides have simplified the implementation a little These slides have simplified the implementation a little bitbit

We have missed out:We have missed out: Explicit type conversions;Explicit type conversions; ““Synchronisation” of critical sections in threadsSynchronisation” of critical sections in threads

The full implementation can be found on the CS288 Web The full implementation can be found on the CS288 Web sitesite

This is taken from JavaBeans by Examples, Henri Jubin, This is taken from JavaBeans by Examples, Henri Jubin, Prentice HallPrentice Hall

Running the BakeryRunning the Bakerypublic class TestApp {public class TestApp {

public static void main(String args[ ]) {public static void main(String args[ ]) {TestApp t = new TestApp( );TestApp t = new TestApp( );

}}

public TestApp( ) {public TestApp( ) {Bakery b = new Bakery( );Bakery b = new Bakery( );Customer c1 = new Customer( 1 );Customer c1 = new Customer( 1 );Customer c2 = new Customer( 2 );Customer c2 = new Customer( 2 );b.addOrderListener( c1 );b.addOrderListener( c1 );b.addOrderListener( c2 );b.addOrderListener( c2 );

}}}}

SummarySummary

We have explored a simple example of a We have explored a simple example of a general Notifier-Observer design patterngeneral Notifier-Observer design pattern

Everything in this example is available in Everything in this example is available in the Java 2 Software Development Kitthe Java 2 Software Development Kit

The trick has been to use a design pattern The trick has been to use a design pattern that allows as many Observers that allows as many Observers (Customers, in our case) to be added as (Customers, in our case) to be added as requiredrequired