21
Object-Oriented Object-Oriented Programming with Programming with Java Java Lecture 6 Lecture 6 Using the Java Event Using the Java Event Model Model

Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

  • View
    222

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

Object-Oriented Object-Oriented Programming with JavaProgramming with Java

Lecture 6Lecture 6

Using the Java Event ModelUsing the Java Event Model

Page 2: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

Using the Java Event ModelUsing the Java Event Model

ContentsContents Quick Review of the Java Event modelQuick Review of the 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

Page 3: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

Java Event ModelJava Event Model

Event SourceEvent Source

Event ListenerEvent Listener

Register Event Listener

Fire Event

EventObject

EventObject

Page 4: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

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

Page 5: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

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

Page 6: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

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

Page 7: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

Bakery.javaBakery.java

public class Bakerypublic class Bakerypublic 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)

Page 8: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

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…

}}

Page 9: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

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.

Page 10: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

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

Page 11: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

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);

}}

Page 12: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

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 // implement in CustomerCustomer

}}

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

}}

Page 13: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

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

Page 14: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

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

Page 15: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

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

… … }}

Page 16: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

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

Page 17: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

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.

Page 18: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

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( );

}}

Page 19: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

WarningWarning

These slides have simplified the implementation These slides have simplified the implementation a little bita little bit

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 The full implementation can be found on the CSM-15 Web siteCSM-15 Web site

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

Page 20: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

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 );

}}}}

Page 21: Object-Oriented Programming with Java Lecture 6 Using the Java Event Model

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