MF1 - PowerPoint PPT Presentation

1 / 39
About This Presentation
Title:

MF1

Description:

Define a one-to-many dependency between objects so that when one ... views can be readily added and deprecated without affecting the model's data or logic ... – PowerPoint PPT presentation

Number of Views:57
Avg rating:3.0/5.0
Slides: 40
Provided by: Mon691
Category:
Tags: deprecated | mf1

less

Transcript and Presenter's Notes

Title: MF1


1
  • Observer pattern
  • MVC

2
Definition
  • Intent
  • Define a one-to-many dependency between objects
    so that when one object changes state, all its
    dependents are notified and updated
    automatically.
  • Motivation
  • Reduces coupling between the classes, and
    increases reusability
  • Also known as Dependents or Publish/Subscribe
  • E.g. Everyone who subscribes to a magazine gets
    the latest version automatically

3
Classic spreadsheet example
4
Todays example
5
Observer pattern
  • Allows observer objects to register interest in
    other objects state (subjects)
  • Whenever the subject changes state, it informs
    all the observer
  • A slightly flawed version exists in java.util
    package (more about this later)
  • The example shows multiple GUIs.
  • The observer pattern is also suitable for a
    single observer, and for non-GUI observers.

6
Observer Pattern
ltltinterfacegtgt Observer update()
ltltinterfacegtgt Subject registerObserver(observer
) removeObserver(observer) notifyObservers()
etc
Subject registerObserver(observer) removeObs
erver(observer) notifyObservers() get/set methods
7
Sequence diagram - pull
8
Observer Pattern for Clock
ltltinterfacegtgt Observer update()
ltltinterfacegtgt Subject registerObserver(observer
) removeObserver(observer) notifyObservers()
ClockModel registerObserver(observer) remove
Observer(observer) notifyObservers() get/set
methods
TimePanel12 update()
TimePanel24 update()
GraphicPanel update()
9
Subject responsibilities 1
  • Subject
  • Stores a list of observers which have registered
    interest. E.g.
  • private ListltObservergt registeredObservers
  • new ArrayListltObservergt()
  • Allows observers to register and deregister at
    will. E.g.
  • public void registerObserver( Observer obs)
  • registeredObservers.add( obs)
  • public void removeObserver( Observer obs)
  • registeredObservers.remove( obs)

10
Subject responsibilities 2
  • Subject
  • Whenever state of subject changes, all registered
    observers are notified by calling update() method
    for each one
  • public void notifyObservers()
  • for(Observer obs registeredObservers)
  • obs.update()

11
ClockModel class
  • Includes
  • constant
  • int MINUTES_IN_HR 60
  • Instance variable
  • int minutes //since midnight
  • Constructor
  • public ClockModel() minutes 0
  • Plus various methods to set the time and get the
    details in different formats
  • Number of hours, number of minutes, String hhmm

12
ClockModel as a subject
  • Includes all clock instance variables and methods
  • Must implement Subject interface
  • public class ClockModel implements Subject
  • PLUS all methods required for the Subject
    interface
  • to manage the list of observers
  • to notify all observers when things change
  • PLUS adding a call to notify observers in any
    methods which alter the time
  • public void setTime24(int hour, int min)
  • minutes hour60 min
  • notifyObservers()

13
Observer responsibilities
  • Observer
  • Registers interest in the state of the subject
  • Calls subjects registerObserver method
  • Whenever its update() method is called, finds out
    the state of the subject and reacts accordingly
  • This often means getting values from the subject

14
GUI Panels
  • There are 3 GUI panels
  • 1 Drawing, 2 text

15
Time Panels
  • The 2 text panels are very similar so have an
    abstract superclass
  • The TimePanel constructor creates the text field
    and adds it to the panel

TimePanel abstract tempText
JTextField modelClockModel abstract update()
void
TimePanel12 update()
TimePanel24 update()
16
Time Panel as an observer
  • The superclass
  • implements the Observer interface
  • abstract public class TimePanel
    extends JPanel implements Observer
  • Includes the subject (clock model) as an instance
    variable
  • Registers with the subject in the constructor
  • model.registerObserver(this)
  • Provides an update method (here by specifying
    that the subclasses must implement it)
  • abstract public void update()

17
Time panel subclasses
  • Most of their functionality is in the superclass
    (creating the panel)
  • Their update functions are different and involve
    getting (pulling) data from the clock model. E.g.
  • public void update()
  • String text model.getTime12()
  • tempText.setText(text)

18
Drawing Panels as an observer
  • The drawing panel behaves in a very similar way
    to the time panel.
  • The only difference is that the update method
    draws the clock using graphics, which are
    probably not covered in this module

19
Push/Pull
  • So far, we have seen data pulled from the Subject
    by the observer
  • An alternative (less pure) design allows the
    Subject to push changed data to the observers
  • As a parameter of the update method

20
Push sequence diagram
aConcrete Observer2
aConcrete Observer1
aConcreteSubject
register()
register()
change()
notify()
update(data)
update(data)
21
java.util.Observer
  • java.util implements an observer pattern
  • There are differences
  • Observable is the Subject
  • Observable is a class not an interface
  • provides addObserver etc.
  • observed classes need to extend Observable
  • Call setChanged() before notifyObservers
  • can provide more flexibility
  • Observer provides update(Observable subj, Object
    arg)
  • Allows both push and pull

22
java.util.Observer
  • Pros
  • All the subject methods for handling observers
    are provided registering, removing, notifying
  • Cons
  • Observable is a class
  • Use by creating subclasses
  • Cant use if your class is already a subclass
    (java does not allow multiple inheritance)
  • Choose java API or provide your own interfaces

23
Observer Pattern (java)
Observable registerObserver(observer) u
nregisterObserver(observer) notifyObservers()
ltltinterfacegtgt Observer update()
Java library classes
Concrete (own) classes
ObB update()
Subject get/set methods
ObA update()
24
Summary
  • Subject does not need to know anything in advance
    about the observers
  • Low coupling between subjects and observers
  • Subject assumes an update method
  • Observer knows how to get updated data
  • This does mean that observers cannot control when
    they receive updates

25
  • Model
  • View
  • Controller

26
Architecture
  • Decouple, decouple, decouple
  • Aiming at maintainable, extensible and robust
    application
  • Maintainable means clean, decoupled architecture
    that is easily understood by new developers.
  • Decoupled implies that different components are
    not reliant on each other
  • Extensible means that developers should be able
    to readily introduce new components without
    having to hack/break the existing code
  • Robust means (as well as being comprehensively
    tested) that we can have different instances
    working together

27
Three Tier Architecture
User Interface
Logic and Volatile Data (state)
Persistent Data Storage
28
Superimposing MVC
User Interface (View)
User Events
Controller
State Change Events
Mapping Events onto Data
Logic and Volatile Data (Model)
Persistent Data Storage
29
Model, View, Controller
  • A Compound Design Pattern
  • Within the top 2 tiers, this compound design
    pattern provides
  • Clarity in design to aid maintainability
  • Modularity so that components can be swapped, ie
    low coupling
  • Multiple views on the same model data
  • Extensibility since controllers and views can be
    readily added and deprecated without affecting
    the models data or logic

30
Extending MVC
View 1
View 2
Controller 2
Controller 1
Logic and Volatile Data (aka Model)
Persistent Data Storage
31
Relies Heavily on 3 Design Patterns
  • Observer
  • publish-subscribe, call-backs, listeners, etc.
  • Strategy deals with interchangeable components
  • Composite, where the GUI is a composite of
    components
  • Observer probably the key player

32
MVC
  • Separate the data, the presentation and the
    business logic
  • The View
  • The visual display of the model
  • The Model
  • The underlying data of your program.
  • The Controller
  • Manages user interaction with the model. The main
    decision making logic is here.

33
Clock Diagram using MVC pattern
1 Controller responds to button clicks
Clock View Displays the clock Is a registered
observer
Clock Controller Responds to change (contains
Listener)
3 Model notifies view to update view gets data
from model
2 Uses Model methods to alter model
Clock Model Looks after hours, minutes Is
Observable /Subject
34
MVC
  • has been called the King of Patterns
  • Theres even a song by James Dempsey about it
    at
  • http//www.youtube.com/watch?vYYvOGPMLVDo

35
MVC Song text
  • Model View, Model View, Model View
    ControllerMVCs the paradigm for factoring your
    code,into functional segments so your brain does
    not explode.To achieve reusability you gotta
    keep those boundaries clean, Model on the one
    side, View on the other, the Controllers in
    between.Model View - Its got three layers like
    Oreos do.Model View creamy ControllerModel
    objects represent your applications raison
    dtre.Custom classes that contain data logic and
    et cetra.You create custom classes in your apps
    problem domain,then you can choose to reuse them
    with all the views,but the model objects stay
    the same
  • Etc etc etc etc etc

36
MVC overview
User gestures
  • VIEW
  • Renders the models
  • Requests updates from models
  • Sends user gestures to controller
  • Allows controller to select view
  • CONTROLLER
  • Defines application behaviour
  • Maps user actions to model updates
  • Selects view for response
  • One for each functionality

View selection
Change notification
State change
State query
  • MODEL
  • Encapsulates application state
  • Responds to state queries
  • Exposes application functionality
  • Notifies views of changes
  • http//java.sun.com/developer/technicalArticles/ja
    vase/mvc/

37
An example from java swing
  • Most swing components are built using MVC, and
    come with a view and a model pre-coupled. E.g.
  • JButton is the View
  • JButton has an underlying model for the data (the
    buttons text), but usually programmers use the
    default
  • The programmer adds their own Controller (the
    ActionListener)
  • For more complex components such as JList or
    JTable, it may be necessary to define your own
    model

38
Summary
  • The observer pattern allows observers to be
    updated about changes to a subject that they have
    registered with.
  • Use pure pattern or the java version
  • It doesnt have to be used with GUIs!
  • The MVC pattern is based mostly on the Observer
    pattern
  • Always separate the Model from the View
  • If possible separate View from Controller
  • MVC underlies SWING

39
Optional extras
  • Add another Observer to the Clock Display program
  • Youll need to register it, and provide an update
    method
  • For simplicity, this observer could just do
    System.out.print or possibly JOptionPane.showMessa
    geDialog(null, message)
  • Read http//www.csis.pace.edu/bergin/mvc/mvcgui.h
    tml
  • Explains mvc with a temperature GUI
  • Quite similar to my clock program but the user
    really interacts with the view
  • Uses java Observer Observable
Write a Comment
User Comments (0)
About PowerShow.com