300 likes | 424 Vues
CSC 313 – Advanced Programming Topics. Lecture 9: Java’s Observable & Observer. Observer Pattern Intent. Efficiently perform 1 -to- many communication Easy to respond dynamically when event(s) occurs Can create many, many possible actions to occur
E N D
CSC 313 – Advanced Programming Topics Lecture 9:Java’s Observable & Observer
Observer Pattern Intent • Efficiently perform 1-to-many communication • Easy to respond dynamically when event(s) occurs • Can create many, many possible actions to occur • Update which actions used throughout execution • Can also use to break mutual dependency • UML class diagram cycles split and managed • Dirty & ugly hack that also is incredibly useful
Registering an Observer • Subjectadds & removes Observers as needed • Adding is simple • Events also simple, call Observers’ update method • Removing not as simple, but still not very hard • Requires some means of holding Observers • Array • ArrayList or LinkedList • HashMap
Registering an Observer • Subjectadds & removes Observers as needed • Adding is simple • Events also simple, call Observers’ update method • Removing not as simple, but still not very hard • Requires some means of holding Observers • Array* • ArrayList or LinkedList • HashMap * Anyone who still did not object to this, fails BIG!
Getting the Word Out • Calling Observers’ update methods is simple • But for call Observerneeds associated information • Not always clear what is best way to share this data • Must understand strengths & weaknesses of each • Push model is easiest of two approaches • Observers get data directly from Subject • Method’s parameters have values to be used • Another approach using pattern’s pull model • Subjectprovides strategy to Observers via a param • To get data, Observeruses strategies methods
Observer Pattern in Java • Java ♥ Observer Pattern & uses everywhere • Find pattern in JButton & ActionListeners • Tracking mouse in Swing using Observer Pattern • Much of the multi-threaded API uses this • Event-based code needs Observers to work • Not limited to Java; true for most OO languages
java.util.Observable • Among original classes included in Java • Works with java.util.Observer interface • Observable manages Observersin code void addObserver(Observer o)void deleteObserver(Observer o)void deleteObservers() intcountObservers()
Handling Updates • Observable approach supports push… void notifyObserver(Object arg) … & pull model available as well void notifyObserver()booleanhasChanged()void clearChanged()void setChanged() • Notifications sent to Observer’s only method void update(Observableo, Object arg)
Using Observable Problem public class CSCClass {private Observable obs;// Lots of unimportant code herepublic void cancelClass() {obs.notifyObservers(“Go drinking!”);} }
Using Observable Problem public class CSCClass {private Observable obs;// Lots of unimportant code herepublic void cancelClass() {obs.notifyObservers(“Go drinking”);} }
Using Observable Problem public class CSCClass {private Observable obs;// Lots of unimportant code herepublic void cancelClass() {obs.notifyObservers(“Go drinking”);} }
Bad & Worse Design Decisions • No update was sent
Bad & Worse Design Decisions • No update was sent; sobriety ruled the day
Bad & Worse Design Decisions • No update was sent; sobriety ruled the day
Bad & Worse Design Decisions • No update was sent; sobriety ruled the day • notifyObservers misnamed horribly • Should be notifyObserversIfChanged • Must call setChangedbefore notifying • Use of notifyObservers inconsistent, too • Calls clearChanged automatically once updates sent
Updated Code public class CSCClass {private Observable obs;// Lots of unimportant code herepublic void cancelClass() {obs.setChanged();obs.notifyObservers(“Go drinking”);} }
Next Attempt public class CSCClass {private Observable obs;// Lots of unimportant code herepublic void cancelClass() {obs.setChanged();obs.notifyObservers(“Go drinking”);} }
Next Attempt public class CSCClass {private Observable obs;// Lots of unimportant code herepublic void cancelClass() {obs.setChanged();obs.notifyObservers(“Go drinking”);} }
Next Attempt public class CSCClass {private Observable obs;// Lots of unimportant code herepublic void cancelClass() {obs.setChanged();obs.notifyObservers(“Go drinking”);} }
Next Attempt public class CSCClass {private Observable obs;// Lots of unimportant code herepublic void cancelClass() {obs.setChanged();obs.notifyObservers(“Go ski”);} } setChanged has protected access
%&#*@ Awful Design • setChanged & clearChangedprotected access • java.util package is sealed; cannot write class for it • Can only be called & used from within subclass • Must write subclass of Observable to use it • As this is Java, that class cannot extend others • Updates received in method of Observer: void update(Observable o, Object arg) • This really means that can onlypush 1 object • Kills point of push model since cannot push much
%&#*@ Awful Design • setChanged & clearChangedprotected access • java.util package is sealed; cannot write class for it • Can only be called & used from within subclass • Must write subclass of Observableto use it • As this is Java, that class cannot extend others • Updates received in method of Observer: void update(Observable o, Object arg) • This really means that can onlypush 1 object • Kills point of push model since cannot push much Useless
Final Attempt public class CSCClassextends Observable {public void cancelClass() {setChanged(); notifyObservers(“Go drinking”);} } public class Student implements Observer {public void update(Observable o, Object arg) { String s = (String)arg; if (!s.equals(“Get here NOW!!!”)) // Go drinking else // Go to class} }
Final Attempt public class CSCClassextends Observable{public void cancelClass() {setChanged(); notifyObservers(“Go drinking”);} } public class Student implements Observer{public void update(Observable o, Object arg) { String s = (String)arg; if (!s.equals(“Get here NOW!!!”)) // Go drinking else // Go to class with a drink} }
Observable Pros & Cons • Cons: • Pros:
Observable Pros & Cons • Cons: • Need a subclass of Observableto use • Must call setChange before notifyObservers • Can push only 1 object to Observers • Pros: • Already has code to add & remove Observers • Easy to rewrite and improve upon this design
For Next Lecture • Two (short) readings available on web • Will start looking into how code is optimized • How does Java run & make programs faster? • What can we do to make our code faster? • Using final can be huge. Why would it matter? • Lab #2 due at week’s end & still on Angel • Make sure that you also check the grading rubric • Use Assignment Submitter when turning it in