C OMP 110 M ODEL -V IEW -C ONTROLLER MVC Instructor: Jason Carter.

Slides:



Advertisements
Similar presentations
INHERITANCE BASICS Reusability is achieved by INHERITANCE
Advertisements

Teaching Inter-Object Design Patterns to Freshmen Prasun Dewan UNC-Chapel Hill.
The Web Warrior Guide to Web Design Technologies
P ROPERTIES OF C OLLABORATIVE U SER I NTERFACES Prasun Dewan Department of Computer Science University of North Carolina at Chapel Hill
C OMP 110 S TATE Instructor: Jason Carter. 2 O UTLINE Instance Variables Procedures Properties Print Statements Println vs. Print Overloading.
Recitation 11 November 11, Today’s Goals:  Automatic refresh  Learn and apply the Observer pattern.
C OMP 110 S TYLE Instructor: Jason Carter. 2 I NTERFACES AND M ORE S TYLE Define contracts between our users and implementers Optional – they may not.
C OMP 110 L OOPS Instructor: Jason Carter. 2 L OOPS More loops Off-by-one errors Infinite loops Nested Loops Animations Concurrency Synchronized methods.
C OMP 110 L OAN C ASE S TUDY Instructor: Jason Carter.
Mari Göransson - KaU - Datavetenskap - DAVD11 1 Java Beans - Events and Properties -
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Dialogs. Displaying Text in a Dialog Box Windows and dialog boxes –Up to this our output has been to the screen –Many Java applications use these to display.
Model View Controller Prasun Dewan Comp 114. Model View Controller Pattern Issue –How to create user-interface objects like object editor Model-View-Controller.
Midterm Exam 75 points 1 min per point Allocate time proportionate to points Closed book Chapters 1-5 (except char) PDF/PS with index and corrections coming.
Program Style Identifier Names Comments Named Constants Avoiding Code Repetition Giving Least Privilege Efficiency Interfaces.
ObjectEditor Prasun Dewan Comp 114. ObjectEditor Automatic user-interface generation. You only write computation code Separate object to do I/O Main just.
Model View Controller Pattern Patterns Model-View-Controller.
Object-Oriented Analysis and Design
Model View Controller Prasun Dewan Comp 114. Model View Controller Pattern Issue –How to create user-interface objects like object editor Model-View-Controller.
State Instance Variables Procedures Properties Print Statements Println Vs Print Overloading J++
Io package as Java’s basic I/O system continue’d.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
Observer Design Pattern Source: Design Patterns – Elements of Reusable Object- Oriented Software; Gamma, et. al.
C OMP 401 P ATTERNS, I NTERFACES AND O BJECT E DITOR Instructor: Prasun Dewan.
TM Introduction to JavaBeans™ Dimitrios Psarros Questra Consulting (716) x225.
C OMP 110/401 C OMPOSITE A NNOTATIONS Instructor: Prasun Dewan.
CSE 331 Software Design & Implementation Dan Grossman Winter 2014 Events, Listeners, and Callbacks (Based on slides by Mike Ernst, David Notkin, Hal Perkins)
Chapter 19 Designing the GUI front-end: the Model-View-Controller pattern.
The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA
C OMP 401: C ONSTRUCTORS AND P OINTERS Instructor: Prasun Dewan (FB 150,
Components Components are specialized self contained Software entities that can be replicated, Customized and inserted into applications. Components come.
Chapter 12 1 TOPIC 13B l Buttons and Action Listeners Window Interfaces Using Swing Objects.
C OMP 110/401 E NCAPSULATION AND L EAST P RIVILEGE Instructor: Prasun Dewan.
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
A NATOMY OF AN I NTERACTIVE A PPLICATION Prasun Dewan Department of Computer Science University of North Carolina at Chapel Hill Code.
Review Class Inheritance, Abstract, Interfaces, Polymorphism, GUI (MVC)
OBSERVER DESIGN PATTERN. Behavioral Patterns  Behavioral patterns are those patterns that are most specifically concerned with communication between.
C OMP 401 A NIMATION : MVC Instructor: Prasun Dewan.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAMMING PRACTICES Model View.
C OMP 401 U SER -I NTERFACE VS. M AIN T HREADS Instructor: Prasun Dewan.
C OMP 401 R EFLECTION AND A CTION O BJECTS Instructor: Prasun Dewan.
1 CSE 331 Model/View Separation and Observer Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia.
Interfaces and Inner Classes
CSE 331 Software Design & Implementation Hal Perkins Winter 2013 Events, Listeners, and Callbacks (slides by Mike Ernst and David Notkin) 1.
The Observer Pattern.
The Observer Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Observer / Observable COMP 401 Fall 2014 Lecture 14 10/7/2014.
C OMP 401 P RACTICAL A PPLICATIONS OF MVC AND O BSERVER : P ROPERTY N OTIFICATION Instructor: Prasun Dewan.
Java - hello world example public class HelloWorld { public static void main (String args[]) { System.out.println("Hello World"); }
C OMP 110/401 D OCUMENTATION : A NNOTATIONS Instructor: Prasun Dewan.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
Java Visual Applications CSIS 3701: Advanced Object Oriented Programming.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
T YPES OF M ODELS Prasun Dewan Department of Computer Science University of North Carolina at Chapel Hill Code available at:
Observer Pattern Context:
Topic: Classes and Objects
Delegates and Events 14: Delegates and Events
Observer Design Pattern
Architectural Patterns for Interactive Software
MVC Paradigm The MVC paradigm breaks applications or interfaces into three parts: the model, the view, and the controller. A --> 25 % B --> 60 % C -->
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Introduction to Behavioral Patterns (1)
Introduction to Event Handling
Recitation 3 September 9, 2011 Wade Gobel.
Constructors, GUI’s(Using Swing) and ActionListner
Advanced ProgramMING Practices
Properties and Collections
Advanced ProgramMING Practices
Observer pattern, MVC, IO & Files
Presentation transcript:

C OMP 110 M ODEL -V IEW -C ONTROLLER MVC Instructor: Jason Carter

2 U SER -I NTERFACE OBJECTS How to reuse code among different user interfaces? How to simultaneously create multiple user interfaces to same object? Different views for same user Slide sorter vs. Outline How to create same or different view for each user sharing an object Distributed presentation

3 C OUNTER Can add arbitrary positive/negative value to an integer Different user interfaces

4 C ONSOLE I NPUT AND O UTPUT

5 C ONSOLE I NPUT AND JO PTION O UTPUT

6 C ONSOLE I NPUT,O UTPUT AND JO PTION O UTPUT

7 I MPLEMENTATION C ONSTRAINT Re-use as much code as possible in the three implementations

8 P ATTERN - FREE I MPLEMENTATION public class ConsoleUI { static int counter = 0; public static void main(String[] args) { System.out.println("Counter: " + counter); while ( true ) { int nextInput = Console.readInt(); if (nextInput == 0) break ; counter += nextInput; System.out.println("Counter: " + counter); }

9 P ATTERN - FREE I MPLEMENTATION import javax.swing.JOptionPane; public class ConsoleUI { static int counter = 0; public static void main(String[] args) { while ( true ) { int nextInput = readInt(); if (nextInput == 0) break ; counter += nextInput; JOptionPane.showMessageDialog( null, “Counter: ” + counterValue); } Counter code is duplicated

10 M ODEL /I NTERACTOR S EPARATION Counter AConsoleUI AMultipleUI AMixedUI Model Model has no UI code and only semantics! Interactor

11 C OMPOSING M ODEL AND I NTERACTOR public static void main (String args[]) { ( new AConsoleUI()).edit ( new ACounter()); }

12 C OUNTER M ODEL public class ACounter implements Counter { int counter = 0; public void add ( int amount) { counter += amount; } public int getValue() { return counter; } Code Reusability Less Duplication Fewer Changes

13 C ONSOLE I NTERACTOR public class AConsoleUI implements ConsoleUI { public void edit (Counter counter) { System.out.println("Counter: " + counter); while ( true ) { int nextInput = Console.readInt(); if (nextInput == 0) return ; counter.add(nextInput); System.out.println("Counter: " + counter.getValue()); } Shared Model Code Input Output

14 M IXED I NTERACTOR public class AMixedUI implements ConsoleUI { public void edit (Counter counter) { while ( true ) { int nextInput = Console.readInt(); if (nextInput == 0) break ; counter.add(nextInput); JOptionPane.showMessageDialog(null, " Counter: " + counter.getValue()); } Shared Model Code Input Output

15 M ULTIPLE I NTERACTOR public class AMultipleUI implements ConsoleUI { public void edit (Counter counter) { System.out.println("Counter: " + counter); while ( true ) { int nextInput = Console.readInt(); if (nextInput == 0) break ; counter.add(nextInput); System.out.println("Counter: " + counter.getValue()); JOptionPane.showMessageDialog(null, " Counter: " + counter.getValue()); } Shared Model Code Input Output

16 D RAWBACKS OF M ONOLITHIC UI Counter AConsoleUI AMultipleUI AMixedUI Duplicated Input Code Duplicated Output Code

17 M ODEL /I NTERACTOR P ATTERN Model Interactor UI Code Computation Code Arbitrary UI unaware methods

18 MVC P ATTERN Model View Write Methods Controller Read Methods Performs Input Performs Output

19 MVC P ATTERN IN C OUNTER Model View add() Controller getValue() Performs Input Performs Output

20 M ULTIPLE V IEWS AND C ONTROLLERS Model Controller 1 Controller 2 Controller 3 Controller 4 View 1 View 2 View 3 View 4

21 S YNCING C ONTROLLERS & V IEW Model Controller 1 Controller 2 Controller 3 Controller 4 View 1 View 2 View 3 View 4

22 O BSERVER /O BSERVABLE P ATTERN Model Controller 1 Controller 2 Controller 3 Controller 4 View 1 View 2 View 3 View 4 Changed model notifies views ObserversObservable

23 O BSERVER /O BSERVABLE P ATTERN Observable 1 Observer 1 Observer 2 Observer 3 Observer N Observable 2

24 O BSERVER WITH MULTIPLE O BSERVABLES A single battle simulation view observing Multiple planes Multiple tanks

25 N OTIFICATION S CHEME Observable 1 Observer 1 Observer 2 Observer 3 Observer N Observable 2 Each observer is registered with observable Each write method in observable calls a notification method in each observer Notification method in observer reads model Each student is registered with professor’s listserv When web page is updated mail sent to students Student reads web page

26 G ENERAL N OTIFICATION S CHEME Observable 1 Observer 1 Observer 2 Observer 3 Observer N Observable 2 Observers may have multiple observerables with common notification method Notification method parameter indicates which observable

27 MVC P ATTERN Model View add() Controller getValue() Performs Input Performs Output Notification Method

28 I MPLEMENTATION DEPENDENT ISSUES How does controller know about model? Model connection method invoked on it By model or some other program Main How is observable registered with observer It registers itself if it knows about observable Model registers it if it knows about observer Some other code registers it Main

29 M ODEL, V IEW AND C ONTROLLER (MVC) Model View add() Controller getValue() Performs Input Performs Output Notification Method Model Connection Method Observer Registration Method

30 C OUNTER O BSERVABLE AND O BSERVER ? public interface ObservableCounter { public void add ( int amount) ; public int getValue() ; // additional methods? } public interface CounterObserver { }

31 C OUNTER O BSERVABLE AND O BSERVER public interface ObservableCounter { public void add ( int amount) ; public int getValue() ; public void addObserver(CounterObserver observer); public void removeObserver(CounterObserver observer); } public interface CounterObserver { public void update(ObservableCounter counter); } Console View, JOption View Called whenever model is updated Updated model

32 C OUNTER M ODEL public class AnObservableCounter implements ObservableCounter { int counter = 0; ObserverHistory observers = new AnObserverHistory(); public void add (int amount) { counter += amount; notifyObservers(); } public int getValue() { return counter; } public void addObserver(CounterObserver observer) { observers.addElement(observer); observer.update( this ); } public void removeObserver(CounterObserver observer) { observers.removeElement(observer); } void notifyObservers() { for ( int observerNum = 0; observerNum < observers.size(); observerNum++) observers.elementAt(observerNum).update(this); } Give this observable initial value Each write method notifies all!

33 C ONSOLE V IEW public class ACounterConsoleView implements CounterObserver { public void update(ObservableCounter counter) { System.out.println("Counter: " + counter.getValue()); }

34 JO PTION V IEW import javax.swing.JOptionPane; public class ACounterJOptionView implements CounterObserver { public void update(ObservableCounter counter) { JOptionPane.showMessageDialog( null, "Counter: " + counter.getValue()); }

35 C ONSOLE C ONTROLLER I NTERFACE public interface CounterController { public void setModel(ObservableCounter theCounter); public void processInput(); }

36 C ONSOLE C ONTROLLER public class ACounterController implements CounterController { ObservableCounter counter; public void setModel(ObservableCounter theCounter) { counter = theCounter; } public void processInput() { while ( true ) { int nextInput = Console.readInt(); if (nextInput == 0) break ; counter.add(nextInput); }

37 C ONSOLE M AIN public static void main (String args[]) { ObservableCounter model = new AnObservableCounter(); model.addObserver( new ACounterConsoleView()); CounterController controller = new ACounterController(); controller.setModel(model); controller.processInput(); }

38 C ONSOLE AND JO PTION M AIN public static main (String args[]) ObservableCounter model = new AnObservableCounter(); model.addObserver ( new ACounterJOptionView()); CounterController controller = new ACounterController(); controller.setModel(model); controller.processInput(); } Shared input code

39 M IXED UI M AIN public static main (String args[]) ObservableCounter model = new AnObservableCounter(); model.addObserver( new AConsoleJOptionView()); model.addObserver ( new ACounterConsoleView()); CounterController controller = new ACounterController(); controller.setModel(model); controller.processInput(); }

40 O BSERVERS THAT ARE NOT VIEWS Spreadsheet cell observes cells on which it depends Monitoring of appliance usage Each time I do setChannel() on TV event logged Any big brother app! Counter observer?

41 R OCKET O BSERVER View added before rocket observer

42 I NSTANCES CREATED AND COMPOSED AnObservable Counter AnObservable Counter ARocketLaunching CounterObserver Controller ACounterConsole View ARocketLauncher

43 R OCKET L AUNCHER public class ARocketLaunchingCounterObserver implements CounterObserver { public void update(ObservableCounter counter) { if (counter.getValue() == 0) launch(); } private void launch() { System.out.println("LIFT OFF!!!"); }

44 R OCKET L AUNCHING M AIN public static void main (String args[]) { ObservableCounter model = new AnObservableCounter(); model.addObserver ( new ACounterConsoleView()); model.addObserver( new ARocketLaunchingCounterObserver()); CounterController controller = new ACounterController(); controller.setModel(model); controller.processInput(); }

45 M ORE ON O BSERVERS Different forms of observers are provided by Java software Some differences in syntax Using term “Listener” instead of “Observer” Some differences in amount of information conveyed to observer about change

46 B ASIC N OTIFICATION public interface CounterObserver { public void update(ObservableCounter counter); } Called when observer is updated Updated Observable

47 I MPLICIT O BSERVER public interface CounterObserver { public void setObservable(ObservableCounter counter); public void update(); } Updated Observable What if observer is in USA and observable in China? Update must make a “long distance” call to read method (getValue()) to update counter state

48 N OTIFICATION WITH C HANGE D ESCRIPTION package models; public interface CounterObserver { public void update(ObservableCounter counter, int newCounterVal); } No need to call read method after notification

49 J AVA JAVA. UTIL.O BSERVER public interface java.util.Observer { public void update(Observable o, Object arg); } “Standard” observer interface talking arbitrary change Object argument Will learn more about Object after inheritance

50 N OTIFICATION WITH C HANGED V ALUE public interface CounterObserver { public void update(ObservableCounter counter, int newCounterVal); } New value of observable attribute

51 N OTIFICATION WITH C HANGE public interface CounterObserver { public void update(ObservableCounter counter, int counterIncrement); } Difference between new and old value of observable attribute Observer may display change to user Observer interested in change does not need to keep old value to determine change Observer interested in absolute value must keep old value

52 N OTIFICATION WITH N EW AND O LD V ALUE public interface CounterObserver { public void update (ObservableCounter counter, int oldCounterValue, int newCounterValue); } Old and new value of observable attribute Observer interested in change does not need to keep old value to determine change Observer interested in absolute value need not keep old value Makes observer harder to code

53 N OTIFICATION WITH S INGLE E VENT O BJECT public interface CounterObserver { public void update( CounterChangeEvent event); } public interface CounterChangeEvent { ObservableCounter getCounter(); int getOldCounterValue(); int getNewCounterValue(); } Easy to pass single object to different methods handling event Can make event info very elaborate Time when event occurred Unique ID for event …. Don’t have to declare parameters for event information fields not of interest Can return object from a function

54 J AVA A CTION E VENT import java.awt.Event; public interface java.awt.ActionListener { public void actionPerformed(ActionEvent e); }

55 O BSERVING M ULTIPLE P ROPERTIES public interface BMISpreadsheet { public double getHeight(); public void setHeight( int newVal); public double getWeight(); public void setWeight( int newWeight) ; public double getBMI(); }

56 S INGLE C OARSE -G RAINED U PDATE public interface BMISpreadsheet { public double getHeight(); public void setHeight( int newVal); public double getWeight() ; public void setWeight( int newWeight) ; public double getBMI(); } public interface BMIObserver { public void update( BMISpreadsheet bmiSpreadsheet); } Coarse grained updated Each setter sends the whole object Observer must determine which property changed

57 M ULTIPLE FINE - GRAINED UPDATES public interface BMISpreadsheet { public double getHeight(); public void setHeight( int newVal); public double getWeight() ; public void setWeight( int newWeight) ; public double getBMI(); } public interface BMIObserver { public void updateHeight ( BMISpreadsheet bmi, int oldHeight, int newHeight); public void updateWeight( BMISpreadsheet bmi, int oldWeight, int newWeight); public void updateBMI( BMISpreadsheet bmi, double oldBMI, double newBMI); }

58 S INGLE FINE - GRAINED UPDATE METHOD public interface BMISpreadsheet { public double getHeight(); public void setHeight ( int newVal); public double getWeight(); public void setWeight( int newWeight) ; public double getBMI(); } public interface BMIObserver { public void update( BMISpreadsheet bmi, String propertyName, Object oldValue, Object newValue); } New methods not needed as new properties added Different setters calls the same update method with different types of values. Can be used for arbitrary property values Can make mistakes “Wght” “One”

59 P ROPERTY C HANGES public interface java.beans.PropertyChangeListener { public void propertyChange (PropertyChangeEvent evt); } public class java.beans.PropertyChangeEvent extends java.util.EventObject { public PropertyChangeEvent (Object source, String propertyName, Object oldValue, Object newValue) {…} public Object getNewValue() {…} public Object getOldValue() {…} public String getPropertyName() {…} …. }

60 P ROPERTY C HANGES If a displayed object defines addPropertyChangeListener(PropertyChangeListener l) { …} ObjectEditor automatically calls it to register itself Setter method can can now notify listeners public void propertyChange(PropertyChangeEvent evt) ObjectEditor reacts by updating display of property Does not have to do polling refresh by calling all getter methods when a setter is invoked. Can disable this polling refresh by invoking View  Auto Refresh command More on this when we discuss animation when it will be a crucial feature