400 likes | 969 Views
Observer pattern MVC. 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
E N D
Observer pattern MVC Observer pattern
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 Observer pattern
Classic spreadsheet example Observer pattern
Today’s example Observer pattern
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. Observer pattern
Observer 1 update() Observer 2 update() For all o in observers o.update(); Calls get methods in subject Observer Pattern <<interface>> Observer update() <<interface>> Subject registerObserver(observer) removeObserver(observer) notifyObservers() etc Subject registerObserver(observer) removeObserver(observer) notifyObservers() get/set methods Observer pattern
aConcrete Observer1 aConcrete Observer2 aConcreteSubject register() register() change() notify() update() get?() update() get?() Sequence diagram - pull Observer pattern
For all o in observers o.update(); Calls get methods Observer Pattern for Clock <<interface>> Observer update() <<interface>> Subject registerObserver(observer) removeObserver(observer) notifyObservers() ClockModel registerObserver(observer) removeObserver(observer) notifyObservers() get/set methods TimePanel12 update() TimePanel24 update() GraphicPanel update() Observer pattern
Subject responsibilities 1 • Subject • Stores a list of observers which have registered interest. E.g. private List<Observer> registeredObservers = new ArrayList<Observer>(); • 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); } Observer pattern
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(); } Observer pattern
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 hh:mm Observer pattern
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 = hour*60 + min; notifyObservers(); } Observer pattern
Observer responsibilities • Observer • Registers interest in the state of the subject • Calls subject’s 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 Observer pattern
GUI Panels • There are 3 GUI panels • 1 Drawing, 2 text Observer pattern
Sets time accordingto own rules 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 #model:ClockModel abstract update() : void TimePanel12 update() TimePanel24 update() Observer pattern
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(); Observer pattern
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); } Observer pattern
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 Observer pattern
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 Observer pattern
Push sequence diagram aConcrete Observer1 aConcrete Observer2 aConcreteSubject register() register() change() notify() update(data) update(data) Observer pattern
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 Observer pattern
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 • Can’t use if your class is already a subclass (java does not allow multiple inheritance) • Choose java API or provide your own interfaces Observer pattern
Observer Pattern (java) <<interface>> Observer update() Observable registerObserver(observer) unregisterObserver(observer) notifyObservers() Java library classes Concrete (own) classes ObB update() Subject get/set methods ObA update() Observer pattern
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 Observer pattern
Model View Controller Observer pattern
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 Observer pattern
Three Tier Architecture User Interface Logic and Volatile Data (state) Persistent Data Storage Observer pattern
Superimposing MVC User Interface (View) User Events Controller State Change Events Mapping Events onto Data Logic and Volatile Data (Model) Persistent Data Storage Observer pattern
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 model’s data or logic Observer pattern
Extending MVC View 1 View 2 Controller 2 Controller 1 Logic and Volatile Data (aka Model) Persistent Data Storage Observer pattern
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 Observer pattern
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. Observer pattern
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 Observer pattern
MVC… • … has been called the King of Patterns • There’s even a song by James Dempsey about it at: • http://www.youtube.com/watch?v=YYvOGPMLVDo Observer pattern
MVC Song text Model View, Model View, Model View ControllerMVC’s 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 Controller’s in between.Model View - It’s got three layers like Oreos do.Model View creamy ControllerModel objects represent your applications raison d’tre.Custom classes that contain data logic and et cetra.You create custom classes in your app’s 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 Observer pattern
http://java.sun.com/developer/technicalArticles/javase/mvc/ 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 query State change MODEL • Encapsulates application state • Responds to state queries • Exposes application functionality • Notifies views of changes Observer pattern
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 button’s 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 Observer pattern
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 doesn’t 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 Observer pattern
Optional extras • Add another Observer to the Clock Display program • You’ll need to register it, and provide an update method • For simplicity, this observer could just do System.out.print or possibly JOptionPane.showMessageDialog(null, message); • Read http://www.csis.pace.edu/~bergin/mvc/mvcgui.html • Explains mvc with a temperature GUI • Quite similar to my clock program but the user really interacts with the view • Uses java Observer & Observable Observer pattern