Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Behavioral Patterns (1)

Similar presentations


Presentation on theme: "Introduction to Behavioral Patterns (1)"— Presentation transcript:

1 Introduction to Behavioral Patterns (1)
11/28/2018 Programming Design Patterns

2 Behavioral and Creational Pattern
Creational patterns involve object instantiation all patterns provide a way to decouple a client from the objects it needs to instantiate. Behavioral patterns concerned with how classes and objects interact and distribute responsibility. Programming Design Patterns 11/28/2018

3 Programming Design Patterns
Design Problem Given a WeatherData object with the following methods getTemperature(); // gets the temp data member getHumidity(); // gets the humidity data member getPressure(); // gets the pressure data member measurementsChanged(); this method is called by some other object whenever the data changes 3 display elements use the new data for display current conditions, forecast, statistics Assume the WeatherData class has access to these data members: currentConditionsDisplay, forecastDisplay, statisticsDisplay Write code for the measurementsChanged() method template provided in the next slide Programming Design Patterns 11/28/2018

4 WeatherData class (attempt 1)
public class WeatherData { private DisplayConditions currentConditions; private DisplayStats statisticsDisplay; private DisplayForecast forecastDisplay; public void measurementsChanged() { // ADD CODE HERE // get the latest values and call the three displays } private float getTemperature() {…} private float getPressure() {…} private float getHumidity() {…} Programming Design Patterns 11/28/2018

5 WeatherData class (attempt 1)
public class WeatherData { Display currentConditions, statisticsDisplay, forecastDisplay; public void measurementsChanged() { // ADD CODE HERE // get the latest values and call the three different displays to // display temp, pressure, and humidty } float getTemperature(); float getPressure(); float getHumidity(); Programming Design Patterns 11/28/2018

6 WeatherData class (attempt 1)
public class WeatherData { // … public void measurementsChanged() { temp = getTemperature(); humidity = getHumidity(); pressure = getPressure(); currentConditionsDisplay.updateConds(temp, humidity, pressure); statisticsDisplay.updateStats(temp, humidity, pressure); forecastDisplay.updateForecast(temp, humidity, preuress); } Programming Design Patterns 11/28/2018

7 WeatherData class (attempt 2)
public class WeatherData { // … public void measurementsChanged() { temp = getTemperature(); humidity = getHumidity(); pressure = getPressure(); currentConditionsDisplay.update(temp, humidity, pressure); statisticsDisplay.update(temp, humidity, pressure); forecastDisplay.update(temp, humidity, pressure); } // Now, what if 5 new display devices need to be added. // What parts of the code need to change? Programming Design Patterns 11/28/2018

8 WeatherData class: rank on design
Cons ?? Pros Programming Design Patterns 11/28/2018

9 WeatherData class: rank on design
Cons For every new display element we need to alter code. We have no way to add (or remove) display elements at run-time. We haven’t separated out the part that changes. Pros: The display elements implement a common interface as a result the same update(…) method is being called Programming Design Patterns 11/28/2018

10 WeatherData class: cons
public class WeatherData { // … public void measurementsChanged() { temp = getTemperature(); humidity = getHumidity(); pressure = getPressure(); currentConditionsDisplay.update(temp, humidity, pressure); statisticsDisplay.update(temp, humidity, pressure); forecastDisplay.update(temp, humidity, pressure); } // Use of currentConditions.update(), statisticsDisplay.update(). If those // instances are created, then it is coding to concrete implementations, though // they are using a common interface. AWT: abstract windowing toolkit Programming Design Patterns 11/28/2018

11 Programming Design Patterns
Listeners in Java AWT When the button is clicked, specific method is coded that listens for the event and prints “Button was clicked”, for example The entity that listens for the event is an observer AWT: abstract windowing toolkit Programming Design Patterns 11/28/2018

12 Programming Design Patterns
Observer Pattern (1) Several objects depend on a single common object with state that will change as the program runs Note that the design needs to scale well With increase in number of state changes and observers Each dependent object needs to know when the state changes without tight coupling of objects Defines a one-to-many dependency between objects so that when one object changes state all its dependents are notified and updated automatically. Programming Design Patterns 11/28/2018

13 Programming Design Patterns
Subject and Observer The object that changes state and needs to notify others is called the subject. It is an abstract class or interface. The observer is an interface that must be implemented by those objects wishing to be informed of the changes in the subject Programming Design Patterns 11/28/2018

14 Programming Design Patterns
Structure The subject has the responsibility to notify all the observers when a change occurs has many Observer update( ) Subject has one ConcreteObserver update( ) ConcreteSubject Programming Design Patterns 11/28/2018

15 Examples of observer pattern
Newspaper publishes news/papers users subscribe whenever a new edition is published users can un-subscribe Events in Java AWT More examples? Publishers + subscribers = Observer Pattern More examples: chat messages Changes in database, setup a trigger Programming Design Patterns 11/28/2018

16 Observer Pattern: definition
Defines a one-to-many dependency between objects so that when one object changes, all of its dependents are notified and updated automatically Programming Design Patterns 11/28/2018

17 Subject, Observer, DisplayElement
Interface Subject What methods should a subject have? Interface Observer specific to the weather station or a generic method? Interface DisplayElement specific to the observer Programming Design Patterns 11/28/2018

18 Subject, Observer, DisplayElement
public interface Subject { public void registerObserver(Observer o); public void removeObserver(Observer o); public void notifyObservers(); // parameter? } public interface Observer { public void update(float temp, float humidity, …); // can you make the parameters generic? // what if the observable parameters change? public interface DisplayElement { public void display(); No parameter is needed for the notifyObserver() method. It just calls the update/notify method on the observers with an object. Or, pass a generic object in update(). Don’t tie it to the current list of parameters being used. Programming Design Patterns 11/28/2018

19 Programming Design Patterns
Subject, Observer public interface Subject { public void registerObserver(Observer o, Filter f); public void removeObserver(Observer o); public void notifyObservers(); // parameter? } public interface Observer { public void update(Object updateValues); public interface Filter { // parameter may vary according to the problem boolean check(String filterString); No parameter is needed for the notifyObserver() method. It just calls the update/notify method on the observers with an object. Or, pass a generic object in update(). Don’t tie it to the current list of parameters being used. Programming Design Patterns 11/28/2018

20 Subject Implementation
public class SubjectImpl { // Vector to store observers and corresponding filters public void notify() { // retrieve filters and observer references // apply filter to determine if the observer should be updated // assume filterRef has been retrieved for an observer, obs. for (…) { if (filterRef.check(filterString) { obs.update(args); } Programming Design Patterns 11/28/2018

21 WeatherData class design
Should it implement an interface? What data members should it have? What should the constructor do? It should have methods from the Subject interface (along with measurementChanged, setMeasurements, etc) It should have a data member to store the list of observers The constructor should initialize the list of observers (array list to null); Programming Design Patterns 11/28/2018

22 ForecastDisplay Observer
Which interface(s) should it implement? What should be passed to it in the constructor? In the constructor, pass it a reference to the Subject, so the observer can register/un-register later on. The observer here also needs to implement the display() interface, along with the observer interface of update(); Programming Design Patterns 11/28/2018

23 Subject and Observer code
Page 58: WeatherData implements Subject Page 59: ForecastDisplay implements Observer In the constructor pass it a reference to the Subject, so the observer can register/un-register later on. The observer here also needs to implement the display() interface, along with the observer interface of update(); Programming Design Patterns 11/28/2018

24 Observer: Push Interface
The observers have no control over when the data is sent to them Also, the observers cannot choose the data that is sent to them what if an observer is interested in just the temperature data? Programming Design Patterns 11/28/2018

25 Observer: Pull Interface
It is possible to change the interface to be “pull” based Do not need to change the update() call at the subject. Observer decides when and what it wants Observers can pull the information whenever they like example: when they wake up from a sleep mode (sensors) observers can pull subset of the information, if they are not interested in all state changes in the subject Programming Design Patterns 11/28/2018

26 Java has built-in Observer Pattern
Has abstract classes for this pattern so need to inherit from them Has a setChanged() method in the Subject why is it useful? page 64 in the book The setChanged(…) is useful so the subject can control when the notifyAll() should be called. It can wait for the changes to be specific (for example only when the temperate changes, will it notify). Programming Design Patterns 11/28/2018

27 Java: update(…) method
Observer Interface: update(Observable o, Object arg) Subject sends a reference to itself as part of the argument provides more flexibility if the observer is passed a reference to the Subject in its constructor a third-party registered the observer with the Subject Programming Design Patterns 11/28/2018

28 Programming Design Patterns
java.util.Observable Observable is a class not an interface downside of this? Forced to subclass it. Programming Design Patterns 11/28/2018

29 Programming Design Patterns
java.util.Observable Observable is a class not an interface downside of this? Forced to subclass it. What if an existing class already extends another class? It cannot be made a Subject. It is not an interface so, cannot have our own implementation of the methods example: cannot have a specialized implementation when a specific order needs to be followed to contact the observers multi-threaded support needs to be added Does not favor composition over inheritance Programming Design Patterns 11/28/2018

30 Programming Design Patterns
11/28/2018

31 Spreadsheet as an example
A spreadsheet illustrates interesting aspects of the pattern Note that cells are observers and subjects Implement a spreadsheet using the observer pattern just the feature on automatic updates Programming Design Patterns 11/28/2018

32 Spreadsheet: cells can be subjects and observers
Subject 3 25 30 Subject 1 a0 1 +b2 Observer1 -17 Observer2 Subject 2 2 91/b0 Programming Design Patterns 11/28/2018


Download ppt "Introduction to Behavioral Patterns (1)"

Similar presentations


Ads by Google