Unformatted text preview:

Observer and DecoratorKenneth M. AndersonUniversity of Colorado, BoulderCSCI 4448/6448 — Lecture 20 — 11/01/2007© University of Colorado, 20071Thursday, November 1, 2007Lecture Goals• Cover Material from Chapters 2 and 3 of the Design Patterns Textbook• Observer Pattern• Decorator Pattern2Thursday, November 1, 2007Observer Pattern• Don’t miss out when something interesting (in your system) happens! • The observer pattern allows objects to keep other objects informed about events occurring within a software system (or across multiple systems)• Its dynamic in that an object can choose to receive notifications or not at run-time• Observer happens to be one of the most heavily used patterns in the Java Development Kit3Thursday, November 1, 2007Chapter Example: Weather MonitoringWeatherStationTempSensorHumiditySensorPressureSensorWeatherDataObjectTabTabTabDocument Windowpulldatadisplaydataprovided what we implementWe need to pull information from the station and then generate “current conditions, weather stats, and a weather forecast”.4Thursday, November 1, 2007WeatherData SkeletongetTemperature()getHumidity()getPressure()measurementsChanged()WeatherDataWe receive a partial implementation of the WeatherData class from our client.They provide three getter methods for the sensor values and an empty measurementsChanged() method that is guaranteed to be called whenever a sensor provides a new valueWe need to pass these values to our three displays… so that’s simple!5Thursday, November 1, 2007First pass at measurementsChanged...12public void measurementsChanged() {34 float temp = getTemperature();5 float humidity = getHumidity();6 float pressure = getPressure();7 8 currentConditionsDisplay.update(temp, humidity, pressure);9 statisticsDisplay.update(temp, humidity, pressure);10 forecastDisplay.update(temp, humidity, pressure);1112}1314...1516Problems?1. The number and type of displays may vary. These three displays are hard coded with no easy way to update them.2. Coding to implementations, not an interface! Although each implementation has adopted the same interface, so this will make translation easy!6Thursday, November 1, 2007Observer Pattern• This situation can benefit from use of the observer pattern• This pattern is similar to subscribing to a hard copy newspaper• A newspaper comes into existence and starts publishing editions• You become interested in the newspaper and subscribe to it• Any time an edition becomes available, you are notified (by the fact that it is delivered to you)• When you don’t want the paper anymore, you unsubscribe• The newspaper’s current set of subscribers can change at any time• Observer is just like this but we call the publisher the “subject” and we refer to subscribers as “observers”7Thursday, November 1, 2007Observer in Action (I)ObserversSubjectObserver 1Observer2Observer3Subject maintains a list of observers8Thursday, November 1, 2007Observer in Action (II)ObserversSubjectObserver 1Observer2Observer3If the Subject changes, it notifies its observers9Thursday, November 1, 2007Observer in Action (III)ObserversSubjectObserver 1Observer2Observer3If needed, an observer may query its subject for more information10Thursday, November 1, 2007Observer In Action (IV)ObserversSubjectObserver 1Observer2Observer3At any point, an observer may join or leave the set of observers Observer411Thursday, November 1, 2007Observer Definition and Structure• The Observer Pattern defines a one-to-many dependency between a set of objects, such that when one object (the subject) changes all of its dependents (observers) are notified and updated automaticallyregisterObserver()removeObserver()notifyObservers()Subject«Interface»update()Observer«Interface»observers*getState()setState()stateConcreteSubjectObserversubject12Thursday, November 1, 2007Observer Benefits• Observer affords a loosely coupled interaction between subject and observer• This means they can interact with very little knowledge about each other• Consider• The subject only knows that observers implement the Observer interface• We can add/remove observers of any type at any time• We never have to modify subject to add a new type of observer• We can reuse subjects and observers in other contexts• The interfaces plug-and-play where ever observer is used• Observers may have to know about the ConcreteSubject class if it provides many different state-related methods• Otherwise, data can be passed to observers via the update() method13Thursday, November 1, 2007Demonstration• Roll Your Own Observer• Using java.util.Observable and java.util.Observable• Observable is a CLASS, a subject has to subclass it to manage observers• Observer is an interface with one defined method: update(subject, data)• To notify observers: call setChanged(), then notifyObservers(data)• Observer in Swing• Listener framework is just another name for the Observer pattern14Thursday, November 1, 2007Decorator Pattern• The Decorator Pattern provides a powerful mechanism for adding new behaviors to an object at run-time• The mechanism is based on the notion of “wrapping” which is just a fancy way of saying “delegation” but with the added twist that the delegator and the delegate both implement the same interface• You start with object A that implements abstract type X• You then create object B that also implements abstract type X• You pass A into B’s constructor and then pass B to A’s client• The client thinks its talking to A but its actually talking to B• B’s methods augment A’s methods to provide new behavior15Thursday, November 1, 2007Why? Open-Closed Principle• The decorator pattern provides yet another way in which a class’s runtime behavior can be extended without requiring modification to the class• This supports the goal of the open-closed principle:• Classes should be open for extension but closed to modification• Inheritance is one way to do this, but composition and delegation are more flexible (and Decorator takes advantage of delegation)• Chapter 3’s “Starbuzz Coffee” example clearly demonstrates why inheritance can get you into trouble and why delegation/composition provides greater run-time flexibility16Thursday, November 1, 2007Starbuzz Coffee• Under pressure to update their “point of sale” system to keep up with their expanding set of beverage products• Started with a Beverage


View Full Document

CU-Boulder CSCI 6448 - Observer and Decorator

Documents in this Course
Struts

Struts

12 pages

Adapter

Adapter

23 pages

Prototype

Prototype

16 pages

Weka

Weka

15 pages

qooxdoo

qooxdoo

16 pages

Django

Django

12 pages

Overview

Overview

22 pages

XNA

XNA

5 pages

Load more
Download Observer and Decorator
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Observer and Decorator and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Observer and Decorator 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?