SlideShare a Scribd company logo
Design Patterns 05/28/10 Week 6: MVC and Other Patterns Jonathan Simon [email_address]
DJView Pg 534 Two Different User Interfaces View – Shows BPM and Beat in real time Control – Enter BPM and click start button.  Increase and Decrease buttons. Pg 535 Start and Stop buttons 05/28/10
DJView: Version 1 //Fields int bpm; Sequencer sequencer; public DJView() { //Display UI Elements CreateDisplayView(); CreateControlView(); //Enable/Disable UI State DisableStopMenuItem(); EnableStartMenuItem(); sequencer = new Sequencer(); } 05/28/10
DJView: Version 1 public void StartButtonPushed() {  sequencer.start(); bpm = 90; sequencer.setTempoInBpm(bpm); DisableStartMenuItem(); EnableStopMenuItem(); DisplayBpm(bpm); } public void StopButtonPushed() { sequencer.turnOff(); bpm = 0; EnableStartMenuItem(); DisableStopMenuItem(); DisplayBpm(bpm); }
DJView: Version 1 public void SetBpm(int bpm) {   this.bpm = bpm; sequencer.setTempoInBpm(bpm);   DisplayBpm(bpm); } public void IncreaseBpm() {   this.bpm = bpm + 1;   sequencer.setTempoInBpm(bpm);   DisplayBpm(bpm); } public void DecreaseBpm() { this.bpm = bpm - 1; sequencer.setTempoInBpm(bpm); DisplayBpm(bpm); }
DJView: Version 1 public void UpdateBeat()  { while (true) { if (sequencer.BeatChanged) DisplayBeat(sequencer.getBeat()); }   }   05/28/10
DJView: Version 1 05/28/10
Requirement Change… Now we need another screen (ArtistView) to display BPM.  (as well other information just as Song Name, Artist, Album Name, year, etc).  Note: ArtistView is not interested in a change in Beat. How can we display BPM? We can modify function DisplayBpm() to update ArtistView and DJView whenever a change is made to BPM. What happens when we create another screen, say AlbumView? 05/28/10
So.. We have a few different screens (DJView, ArtistView, AlbumView) that are all interested whenever we have a change in data state (BPM or Beat).  Some screens are interested in change in BPM, others change Beat, and some changes in both. Currently, we have to update DJView whenever we want to add another screen that is interested in changes in BPM or Beat. What pattern is screaming to be used? 05/28/10
Creating a Subject We need a Subject that contains the data state that we know is changing. In this example, what should fields should go in our Subject? How many different events should our Subject expose? How do we “glue” our Observers to this Subject? 05/28/10
Subject = BeatModel public class BeatModel  { int bpm; Sequencer sequencer; public void initialize() { sequencer = new Sequencer(); } public void RegisterObserver(BeatObserver o) { } public void RemoveObserver(BeatObserver o) { } public void NotifyBeatObservers() { } public void RegisterObserver(BPMObserver o) { } public void RemoveObserver(BPMObserver o) { } public void NotifyBpmObservers() { } }
BeatObserver and BPMObserver public interface BeatObserver { void updateBeat(); } public interface BPMObserver { void updateBPM(); } 05/28/10
DJView: Version 2 //Fields int bpm; Sequencer sequencer; public DJView() { //Display UI Elements CreateDisplayView(); CreateControlView(); //Enable/Disable UI State DisableStopMenuItem(); EnableStartMenuItem(); sequencer = new Sequencer(); } 05/28/10 Changes???
DJView: Version 2 //Fields BeatModel model ; public DJView() { //Display UI Elements CreateDisplayView(); CreateControlView(); //Enable/Disable UI State DisableStopMenuItem(); EnableStartMenuItem(); model = new BeatModel(); model.initialize(); } 05/28/10
DJView: Version 2 public void StartButtonPushed() {  sequencer.start(); bpm = 90; sequencer.setTempoInBpm(bpm); DisableStartMenuItem(); EnableStopMenuItem(); DisplayBpm(bpm); } public void StopButtonPushed() { sequencer.turnOff(); bpm = 0; EnableStartMenuItem(); DisableStopMenuItem(); DisplayBpm(bpm); } Does DJView have a direct reference : To sequencer?  To bpm field?
DJView: Version 2 public void StartButtonPushed() { model.on(); DisableStartMenuItem(); EnableStopMenuItem(); DisplayBpm(bpm); } public void StopButtonPushed() { model.off(); EnableStartMenuItem(); DisableStopMenuItem(); DisplayBpm(bpm); } 05/28/10 What should we do with this DisplayBpm function? What  interfaces does DJView need to implement? Remember BeatModel…
DJView: Version 2 public class DJView :  BeatObserver, BPMObserver  { public void updateBeat() { //Display change in Beat in the UI } public void updateBpm() { int bpm = model.getBpm(); if (bpm == 0)   //Display "offline" else  //Display "Current BPM" with value } } } } 05/28/10 What are we missing?
DJView: Version2 public DJView() {   //Display UI Elements CreateDisplayView(); CreateControlView(); //Enable/Disable UI State DisableStopMenuItem(); EnableStartMenuItem(); model = new BeatModel(); model.initialize(); model.RegisterObserver((BeatObserver)this); model.RegisterObserver((BPMObserver)this); } 05/28/10
DJView: Version 2 public void StartButtonPushed() { model.on(); DisableStartMenuItem(); EnableStopMenuItem(); } public void StopButtonPushed() { model.off(); EnableStartMenuItem(); DisableStopMenuItem(); } public void SetBpm(int bpm) { model.setBPM(bpm); } public void IncreaseBpm() { model.increaseBpm(); } public void DecreaseBpm() { model.decreaseBpm(); }
Version 2 05/28/10 Notice beatObservers and bpmObservers in BeatModel.
View and Model We now have a View and a Model The View is also an Observer.  It is interested in changes in the Model. When the Model has a data change, the View gets notified (updateBPM).  The View then gets data from the Model (getBPM). We can have multiple Views all interested in this Model. 05/28/10
Multiple Views w/One Model 05/28/10 Question:  Does the Model know any specific details about the UI elements on the View?
Definition (Partial): Model Contains the data, state, and application logic. State changes can occur internally or externally. (more on this later). When a change of state occurs, the Model sends a notification message. The Model doesn’t have any direct references to the Views that need it. (Since the Views registers themselves with the Model). 05/28/10
Definition (Partial): View Graphic User Interface. It is the “window” to the model.  View registers with the Model for notification of certain events. When notified by the Model, the View asks the Model for state information.  View must have a direct reference to the Model in order to get data.  (can also be an interface the Model uses) 05/28/10
Requirement Change We need to change all of these views from a Windows application to a Web application. We would like to minimize the amount of code that we need to re-write for the new user interface. Let’s look at the DJView code again.. 05/28/10
DJView: Version 2 public DJView() { CreateDisplayView(); CreateControlView(); DisableStopMenuItem(); EnableStartMenuItem(); //Hidden: Create model, initialize and register observers } public void StartButtonPushed() { model.on(); DisableStartMenuItem(); EnableStopMenuItem(); } public void updateBeat() { ... } public void updateBPM()  { ... } We know that we cannot re-use UI elements when we change Views.
Challenge We want to separate elements from DJView that vary from the things that do not vary. What varies? What does not vary? 05/28/10
What Varies Internals of CreateDisplayView()  + CreateControlView() Internals of all of the Disable/Enable methods The internals of the updateBeat and updateBPM  that has to do with updating UI How events are associated with UI element What does not vary The sequence of events.  For example, StartButtonPushed has a specific set of steps. Calling the Model to do something (on(), off()) Registering View with the Model The internals of the updateBPM that has to do with getting data from the Model 05/28/10
Inheritance Base View class that contains: Reference to BeatModel Template Pattern to define known set of steps; use abstract methods for pieces that need to be implemented by sub class. Each subclass just defines the UI specific elements. What problems will we encounter? 05/28/10
Inheritance (cont) We can’t inherit form the base View  and  the specific UI form (which contains a lot of functionality for interacting with UI elements) We would need to inherit from the Base View and wrap the specific UI element (Windows or Web form) and then expose what we need. (Adapter Pattern!) This would be painful… 05/28/10
Composition View just contains the UI elements and functions that manipulate the UI elements  ( What Varies ) View associates UI element with a handler. ( What Varies ) The UI handler may do a special sequence of events (which may manipulate a combination of model changes and UI updates). This is  What Not Varies . Here is our separation of View and Controller (the New Guy). 05/28/10
What about the Model? The View interacts with the Model in two ways: Sends a message to the Controller to update the Model.  (setBPM, increase, decrease) Gets notified when Model changes (updateBeat, updateBPM) 05/28/10
DJView: Version 3 (Pt 1) public class DJView : BeatObserver, BPMObserver { BeatModel model; BeatController controller; public DJView(BeatModel model, BeatController controller) { this.model = model; this.controller = controller;  model.RegisterObserver((BeatObserver)this); model.RegisterObserver((BPMObserver)this); }   public void updateBeat()  { . . }   public void updateBPM() { . . } 05/28/10 Note: The only reason that View needs Model is for registering of events and getting state from Model.
DJView: Version 3 (Pt 2) public void StartButtonPushed() { controller.start(); } public void StopButtonPushed() { controller.stop(); } public void SetBpm(int bpm) { controller.setBPM(bpm); } public void IncreaseBpm() { controller.increaseBPM(); } public void DecreaseBpm() { controller.decreaseBPM(); } 05/28/10 The View delegates all actions to the Controller.
DJView: Version 3 (Pt 3) //Lastly, we have all of the functions that directly manipulate //UI elements in the View.  These functions are called externally //by the Controller! public void CreateDisplayView() { } public void CreateControlView() { } public void DisableStopMenuItem() { } public void EnableStopMenuItem() { } public void DisableStartMenuItem() { } public void EnableStartMenuItem() { } 05/28/10 NOTE: If we have to port this View from Windows to Web, here is where the crux of our changes will occur.
BeatController public class BeatController { BeatModel model; DJView view; public BeatController(BeatModel model) this.model = model; view = new DJView(model, this); view.CreateDisplayView(); view.CreateControlView(); view.DisableStopMenuItem(); view.EnableStartMenuItem(); model.initialize(); } Why???
BeatController public void start() { model.on(); view.DisableStartMenuItem(); view.EnableStopMenuItem(); } public void stop() { model.off(); view.EnableStartMenuItem(); view.DisableStopMenuItem(); } public void setBPM(int bpm) { model.setBPM(bpm); } 05/28/10 Controller sends a message to Model to update data…and sends a message back to the View. Note: Not showing the Model here. It is exactly the same!
The Big Picture 05/28/10 See diagram on page 530.
Definition: Model Contains the data, state, and application logic. State changes can occur internally or externally (by a message from the Controller) When a change of state occurs, the Model sends a notification message to the Views that want to be notified. The Model doesn’t have any direct references to the Views or Controllers that need it.  05/28/10
Definition: View Graphic User Interface. It is the “window” to the model.  View registers with the Model for notification of certain events. When notified by the Model, the View asks the Model for state information.  View must have a direct reference to the Model in order to get data.  (can also be an interface the Model uses) View delegates actions to the Controller. 05/28/10
Definition: Controller Handles user actions initiated on the View. Informs the Model of any data changes. When applicable, tells the View to change it’s UI state. 05/28/10
Lab: Part I In BeatController.start() function does three things: Sends on() message to the Model Sends DisableStartMenuItem() message to the View Sends EnableStopMenuItem() message to the View. Then we get a requirement that the end user needs to change the Mode (Basic or Advanced) at any time.  If user calls start() during Basic mode, the same functionality occurs. If user calls start() during Advanced mode, the Basic mode functionality occurs, but in addition, the UI displays a video of the song. What can we do?  What pattern can help us?
Lab: Part II Let’s say we need to add permissions. Which object should be modified? (Model, View, Controller) Let’s say a change in the Model needs to result in the enabling and disabling of certain UI elements in the View.  What can we do? 05/28/10
Answer : Part I BeatController can be an abstract class with default implementation for all methods, except start (which can be marked abstract) Create two classes that inherit from BeatController  (Basic and Advanced). Each class defines the unique behavior of start. Associate the View with the appropriate version of BeatController. Use Strategy Pattern to change behavior at run time. 05/28/10
Answer: Part II Controller.  We could easily create a Permission object that is accessed by the Controller.  This has the benefit of keeping permission-related code out of the View. Two Answers: The View can easily respond to the change in the Model and set the appropriate UI elements; however, that is putting more business logic in the View. Controller can become an Observer of certain events in the Model (in addition to the View!).  If a certain change of state occurs in the Model, the Controller can tell the View which UI elements to change.  05/28/10
Testing Testing is a lot easier with MVC. Unit Tests can target the Controller and Model. It is harder to unit test the View. 05/28/10
Frameworks for MVC Spring MVC Java Swing Windows Presentation Foundation (WPF) ASP.NET MVC Framework PureMVC Bistro Apache Struts And many more… 05/28/10
Model View Presenter (MVP) Derivative of MVC. Focuses on the Presentation Layer. For example, interaction of different UI elements on a form. References http://en.wikipedia.org/wiki/Model-view-presenter http://www.mvcsharp.org/   05/28/10
Other Patterns Iterator Composite Builder Façade State Chain of Responsibility Flyweight Memento 05/28/10
Iterator GoF Intent: “Provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.” There are different types of “aggregate objects” Collection ArrayList List<> Array  string[] 05/28/10
Iterator (cont) Each of these objects have different ways of looping through and accessing different elements. Iterator patterns hides the implementation of the aggregate object from the clients that access it. Advantage: You can change an ArrayList into a List<> without breaking clients that use you it. 05/28/10
Composite GoF Intent: “allows you to compose objects into tree structures to represent whole-part hierarchies.  Composite lets clients treat individual objects and composition of objects uniformly.” Think of a tree hierarchy Business objects User Interface elements (Window    Panel    Button) A Node (with Children) and a Leaf Node are all treated the same. 05/28/10
Composite (cont) Example: Windows form where all UI elements are in a tree.  Message is sent to top node to “disable all elements”.  The tree is traversed and Disable message is applied to each node in the tree. Composite and Iterator are often used together.  05/28/10
Builder Encapsulate the construction of a product and allow it to be constructed in steps. Good for the creation of complex objects. Client sends multiple messages to the Builder for creating certain parts of the structure.  Then Builder returns Composite result. 05/28/10
Facade “ Provides a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use”. Example, communication between Business and Data Layer. 05/28/10
State Pattern GoF Intent: “Allows an object to alter its behavior when its internal state changes. The object will appear to change its class.” Strategy Pattern – behavior change due to an external change.  (Remember the setBehavior() method).  The Clients had to be aware of the different possible Strategies. State is basically like Strategy; however, changes occur internally.  05/28/10
Chain of Responsibility “ Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.” Each object in chain acts as a handler. If it cannot handle the request, passes it to the next object in the chain. Often using in Windows system for handling events generated by keyboard or mouse. 05/28/10
Flyweight GoF Intent: “Use sharing to support large numbers of fine-grained objects efficiently.” Addresses memory issues. Instead of having 100 large objects that take up memory: One stateless object  Manager object that contains the state of the 100 objects Single instances will not be able to behave independently from other instances.  (Probably better for read-only purposes!) 05/28/10
Memento Be able to return object to a previous state. Handle undo. 05/28/10
Next Steps? Read the rest of the book! Buy the Gang of Four book to get more details on the patterns mentioned in this book. Understand commonly used frameworks MVC Spring Dependency Injection 05/28/10
Martin Fowler http://www.martinfowler.com/ Refactoring: Improving the Design of Existing Code Patterns of Enterprise Application Architecture  05/28/10

More Related Content

PPT
Command and Adapter Pattern
PPT
Java swing
PDF
Design patterns in the 21st Century
DOC
Super components en Pascal
PDF
Bot builder v4 HOL
PPTX
Complete java swing
PPTX
Dagger 2. The Right Way to Dependency Injections
Command and Adapter Pattern
Java swing
Design patterns in the 21st Century
Super components en Pascal
Bot builder v4 HOL
Complete java swing
Dagger 2. The Right Way to Dependency Injections

What's hot (11)

PDF
Dagger 2. Right way to do Dependency Injection
PDF
04b swing tutorial
PPTX
Mvp - типичные задачи и способ их решения в Moxy
PPTX
Dagger for dummies
PPTX
RxJava 2 Reactive extensions for the JVM
PDF
Advanced Dagger talk from 360andev
PPTX
Beat the Clock: Background Tasking in Windows 8
PDF
Тестирование на Android с Dagger 2
PPTX
Java- GUI- Mazenet solution
PDF
Architecting your GWT applications with GWT-Platform - Lesson 02
PPTX
Dagger 2. Right way to do Dependency Injection
04b swing tutorial
Mvp - типичные задачи и способ их решения в Moxy
Dagger for dummies
RxJava 2 Reactive extensions for the JVM
Advanced Dagger talk from 360andev
Beat the Clock: Background Tasking in Windows 8
Тестирование на Android с Dagger 2
Java- GUI- Mazenet solution
Architecting your GWT applications with GWT-Platform - Lesson 02
Ad

Viewers also liked (17)

PPT
Strategy and Template Pattern
PPT
Factory and Abstract Factory
PPT
Observer and Decorator Pattern
PPT
Introduction to Design Patterns and Singleton
PPT
Design Patterns (Examples in .NET)
PPTX
Software design patterns ppt
PDF
CLTL python course: Object Oriented Programming (2/3)
PPTX
Desing pattern prototype-Factory Method, Prototype and Builder
PPT
Chain of responsibility
PPTX
Chain of Responsibility Pattern
PPS
Design Patterns For 70% Of Programmers In The World
PDF
Software Design Patterns in Laravel by Phill Sparks
PPT
Operating system.ppt (1)
PPTX
Operating system overview concepts ppt
PPTX
Mac OS(Operating System)
PDF
How to Make Awesome SlideShares: Tips & Tricks
PDF
Getting Started With SlideShare
Strategy and Template Pattern
Factory and Abstract Factory
Observer and Decorator Pattern
Introduction to Design Patterns and Singleton
Design Patterns (Examples in .NET)
Software design patterns ppt
CLTL python course: Object Oriented Programming (2/3)
Desing pattern prototype-Factory Method, Prototype and Builder
Chain of responsibility
Chain of Responsibility Pattern
Design Patterns For 70% Of Programmers In The World
Software Design Patterns in Laravel by Phill Sparks
Operating system.ppt (1)
Operating system overview concepts ppt
Mac OS(Operating System)
How to Make Awesome SlideShares: Tips & Tricks
Getting Started With SlideShare
Ad

Similar to MVC and Other Design Patterns (20)

PDF
Game Programming I - Introduction
PPT
myslide6
PPT
NewSeriesSlideShare
PPT
myslide1
PPT
0106 debugging
PDF
CodePool Liverpool 2013 - Microsoft Gadgeteer Presentation
PDF
java presentation on Swings chapter java presentation on Swings
PPT
A View of MPC Control from Operations to Design
PDF
Table maintenance generator and its modifications
PPTX
Hack2the future Microsoft .NET Gadgeteer
PDF
User Guide of Regression Test & Validation Tool (v1.0)
DOCX
Dynamics ax 2012 workflow development
PDF
Lsmw for master data upload simple explanation
DOC
Basic Debugging
DOC
Abapdebuggingfrombasictoadvance 140214043218-phpapp01
PDF
Integrating Angular js & three.js
DOCX
Kalyan 27 oct 2018
PDF
Data warehousing unit 5.2
DOCX
SAP BPC Learning Notes and Insights.docx
PPT
05 b 01workflowcustomizing
Game Programming I - Introduction
myslide6
NewSeriesSlideShare
myslide1
0106 debugging
CodePool Liverpool 2013 - Microsoft Gadgeteer Presentation
java presentation on Swings chapter java presentation on Swings
A View of MPC Control from Operations to Design
Table maintenance generator and its modifications
Hack2the future Microsoft .NET Gadgeteer
User Guide of Regression Test & Validation Tool (v1.0)
Dynamics ax 2012 workflow development
Lsmw for master data upload simple explanation
Basic Debugging
Abapdebuggingfrombasictoadvance 140214043218-phpapp01
Integrating Angular js & three.js
Kalyan 27 oct 2018
Data warehousing unit 5.2
SAP BPC Learning Notes and Insights.docx
05 b 01workflowcustomizing

Recently uploaded (20)

PDF
Approach and Philosophy of On baking technology
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Empathic Computing: Creating Shared Understanding
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Modernizing your data center with Dell and AMD
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Electronic commerce courselecture one. Pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Cloud computing and distributed systems.
Approach and Philosophy of On baking technology
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Understanding_Digital_Forensics_Presentation.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Empathic Computing: Creating Shared Understanding
Network Security Unit 5.pdf for BCA BBA.
Per capita expenditure prediction using model stacking based on satellite ima...
Modernizing your data center with Dell and AMD
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Electronic commerce courselecture one. Pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Review of recent advances in non-invasive hemoglobin estimation
Mobile App Security Testing_ A Comprehensive Guide.pdf
Chapter 3 Spatial Domain Image Processing.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
20250228 LYD VKU AI Blended-Learning.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Encapsulation_ Review paper, used for researhc scholars
Cloud computing and distributed systems.

MVC and Other Design Patterns

  • 1. Design Patterns 05/28/10 Week 6: MVC and Other Patterns Jonathan Simon [email_address]
  • 2. DJView Pg 534 Two Different User Interfaces View – Shows BPM and Beat in real time Control – Enter BPM and click start button. Increase and Decrease buttons. Pg 535 Start and Stop buttons 05/28/10
  • 3. DJView: Version 1 //Fields int bpm; Sequencer sequencer; public DJView() { //Display UI Elements CreateDisplayView(); CreateControlView(); //Enable/Disable UI State DisableStopMenuItem(); EnableStartMenuItem(); sequencer = new Sequencer(); } 05/28/10
  • 4. DJView: Version 1 public void StartButtonPushed() { sequencer.start(); bpm = 90; sequencer.setTempoInBpm(bpm); DisableStartMenuItem(); EnableStopMenuItem(); DisplayBpm(bpm); } public void StopButtonPushed() { sequencer.turnOff(); bpm = 0; EnableStartMenuItem(); DisableStopMenuItem(); DisplayBpm(bpm); }
  • 5. DJView: Version 1 public void SetBpm(int bpm) { this.bpm = bpm; sequencer.setTempoInBpm(bpm); DisplayBpm(bpm); } public void IncreaseBpm() { this.bpm = bpm + 1; sequencer.setTempoInBpm(bpm); DisplayBpm(bpm); } public void DecreaseBpm() { this.bpm = bpm - 1; sequencer.setTempoInBpm(bpm); DisplayBpm(bpm); }
  • 6. DJView: Version 1 public void UpdateBeat() { while (true) { if (sequencer.BeatChanged) DisplayBeat(sequencer.getBeat()); } } 05/28/10
  • 7. DJView: Version 1 05/28/10
  • 8. Requirement Change… Now we need another screen (ArtistView) to display BPM. (as well other information just as Song Name, Artist, Album Name, year, etc). Note: ArtistView is not interested in a change in Beat. How can we display BPM? We can modify function DisplayBpm() to update ArtistView and DJView whenever a change is made to BPM. What happens when we create another screen, say AlbumView? 05/28/10
  • 9. So.. We have a few different screens (DJView, ArtistView, AlbumView) that are all interested whenever we have a change in data state (BPM or Beat). Some screens are interested in change in BPM, others change Beat, and some changes in both. Currently, we have to update DJView whenever we want to add another screen that is interested in changes in BPM or Beat. What pattern is screaming to be used? 05/28/10
  • 10. Creating a Subject We need a Subject that contains the data state that we know is changing. In this example, what should fields should go in our Subject? How many different events should our Subject expose? How do we “glue” our Observers to this Subject? 05/28/10
  • 11. Subject = BeatModel public class BeatModel { int bpm; Sequencer sequencer; public void initialize() { sequencer = new Sequencer(); } public void RegisterObserver(BeatObserver o) { } public void RemoveObserver(BeatObserver o) { } public void NotifyBeatObservers() { } public void RegisterObserver(BPMObserver o) { } public void RemoveObserver(BPMObserver o) { } public void NotifyBpmObservers() { } }
  • 12. BeatObserver and BPMObserver public interface BeatObserver { void updateBeat(); } public interface BPMObserver { void updateBPM(); } 05/28/10
  • 13. DJView: Version 2 //Fields int bpm; Sequencer sequencer; public DJView() { //Display UI Elements CreateDisplayView(); CreateControlView(); //Enable/Disable UI State DisableStopMenuItem(); EnableStartMenuItem(); sequencer = new Sequencer(); } 05/28/10 Changes???
  • 14. DJView: Version 2 //Fields BeatModel model ; public DJView() { //Display UI Elements CreateDisplayView(); CreateControlView(); //Enable/Disable UI State DisableStopMenuItem(); EnableStartMenuItem(); model = new BeatModel(); model.initialize(); } 05/28/10
  • 15. DJView: Version 2 public void StartButtonPushed() { sequencer.start(); bpm = 90; sequencer.setTempoInBpm(bpm); DisableStartMenuItem(); EnableStopMenuItem(); DisplayBpm(bpm); } public void StopButtonPushed() { sequencer.turnOff(); bpm = 0; EnableStartMenuItem(); DisableStopMenuItem(); DisplayBpm(bpm); } Does DJView have a direct reference : To sequencer? To bpm field?
  • 16. DJView: Version 2 public void StartButtonPushed() { model.on(); DisableStartMenuItem(); EnableStopMenuItem(); DisplayBpm(bpm); } public void StopButtonPushed() { model.off(); EnableStartMenuItem(); DisableStopMenuItem(); DisplayBpm(bpm); } 05/28/10 What should we do with this DisplayBpm function? What interfaces does DJView need to implement? Remember BeatModel…
  • 17. DJView: Version 2 public class DJView : BeatObserver, BPMObserver { public void updateBeat() { //Display change in Beat in the UI } public void updateBpm() { int bpm = model.getBpm(); if (bpm == 0) //Display &quot;offline&quot; else //Display &quot;Current BPM&quot; with value } } } } 05/28/10 What are we missing?
  • 18. DJView: Version2 public DJView() { //Display UI Elements CreateDisplayView(); CreateControlView(); //Enable/Disable UI State DisableStopMenuItem(); EnableStartMenuItem(); model = new BeatModel(); model.initialize(); model.RegisterObserver((BeatObserver)this); model.RegisterObserver((BPMObserver)this); } 05/28/10
  • 19. DJView: Version 2 public void StartButtonPushed() { model.on(); DisableStartMenuItem(); EnableStopMenuItem(); } public void StopButtonPushed() { model.off(); EnableStartMenuItem(); DisableStopMenuItem(); } public void SetBpm(int bpm) { model.setBPM(bpm); } public void IncreaseBpm() { model.increaseBpm(); } public void DecreaseBpm() { model.decreaseBpm(); }
  • 20. Version 2 05/28/10 Notice beatObservers and bpmObservers in BeatModel.
  • 21. View and Model We now have a View and a Model The View is also an Observer. It is interested in changes in the Model. When the Model has a data change, the View gets notified (updateBPM). The View then gets data from the Model (getBPM). We can have multiple Views all interested in this Model. 05/28/10
  • 22. Multiple Views w/One Model 05/28/10 Question: Does the Model know any specific details about the UI elements on the View?
  • 23. Definition (Partial): Model Contains the data, state, and application logic. State changes can occur internally or externally. (more on this later). When a change of state occurs, the Model sends a notification message. The Model doesn’t have any direct references to the Views that need it. (Since the Views registers themselves with the Model). 05/28/10
  • 24. Definition (Partial): View Graphic User Interface. It is the “window” to the model. View registers with the Model for notification of certain events. When notified by the Model, the View asks the Model for state information. View must have a direct reference to the Model in order to get data. (can also be an interface the Model uses) 05/28/10
  • 25. Requirement Change We need to change all of these views from a Windows application to a Web application. We would like to minimize the amount of code that we need to re-write for the new user interface. Let’s look at the DJView code again.. 05/28/10
  • 26. DJView: Version 2 public DJView() { CreateDisplayView(); CreateControlView(); DisableStopMenuItem(); EnableStartMenuItem(); //Hidden: Create model, initialize and register observers } public void StartButtonPushed() { model.on(); DisableStartMenuItem(); EnableStopMenuItem(); } public void updateBeat() { ... } public void updateBPM() { ... } We know that we cannot re-use UI elements when we change Views.
  • 27. Challenge We want to separate elements from DJView that vary from the things that do not vary. What varies? What does not vary? 05/28/10
  • 28. What Varies Internals of CreateDisplayView() + CreateControlView() Internals of all of the Disable/Enable methods The internals of the updateBeat and updateBPM that has to do with updating UI How events are associated with UI element What does not vary The sequence of events. For example, StartButtonPushed has a specific set of steps. Calling the Model to do something (on(), off()) Registering View with the Model The internals of the updateBPM that has to do with getting data from the Model 05/28/10
  • 29. Inheritance Base View class that contains: Reference to BeatModel Template Pattern to define known set of steps; use abstract methods for pieces that need to be implemented by sub class. Each subclass just defines the UI specific elements. What problems will we encounter? 05/28/10
  • 30. Inheritance (cont) We can’t inherit form the base View and the specific UI form (which contains a lot of functionality for interacting with UI elements) We would need to inherit from the Base View and wrap the specific UI element (Windows or Web form) and then expose what we need. (Adapter Pattern!) This would be painful… 05/28/10
  • 31. Composition View just contains the UI elements and functions that manipulate the UI elements ( What Varies ) View associates UI element with a handler. ( What Varies ) The UI handler may do a special sequence of events (which may manipulate a combination of model changes and UI updates). This is What Not Varies . Here is our separation of View and Controller (the New Guy). 05/28/10
  • 32. What about the Model? The View interacts with the Model in two ways: Sends a message to the Controller to update the Model. (setBPM, increase, decrease) Gets notified when Model changes (updateBeat, updateBPM) 05/28/10
  • 33. DJView: Version 3 (Pt 1) public class DJView : BeatObserver, BPMObserver { BeatModel model; BeatController controller; public DJView(BeatModel model, BeatController controller) { this.model = model; this.controller = controller; model.RegisterObserver((BeatObserver)this); model.RegisterObserver((BPMObserver)this); } public void updateBeat() { . . } public void updateBPM() { . . } 05/28/10 Note: The only reason that View needs Model is for registering of events and getting state from Model.
  • 34. DJView: Version 3 (Pt 2) public void StartButtonPushed() { controller.start(); } public void StopButtonPushed() { controller.stop(); } public void SetBpm(int bpm) { controller.setBPM(bpm); } public void IncreaseBpm() { controller.increaseBPM(); } public void DecreaseBpm() { controller.decreaseBPM(); } 05/28/10 The View delegates all actions to the Controller.
  • 35. DJView: Version 3 (Pt 3) //Lastly, we have all of the functions that directly manipulate //UI elements in the View. These functions are called externally //by the Controller! public void CreateDisplayView() { } public void CreateControlView() { } public void DisableStopMenuItem() { } public void EnableStopMenuItem() { } public void DisableStartMenuItem() { } public void EnableStartMenuItem() { } 05/28/10 NOTE: If we have to port this View from Windows to Web, here is where the crux of our changes will occur.
  • 36. BeatController public class BeatController { BeatModel model; DJView view; public BeatController(BeatModel model) this.model = model; view = new DJView(model, this); view.CreateDisplayView(); view.CreateControlView(); view.DisableStopMenuItem(); view.EnableStartMenuItem(); model.initialize(); } Why???
  • 37. BeatController public void start() { model.on(); view.DisableStartMenuItem(); view.EnableStopMenuItem(); } public void stop() { model.off(); view.EnableStartMenuItem(); view.DisableStopMenuItem(); } public void setBPM(int bpm) { model.setBPM(bpm); } 05/28/10 Controller sends a message to Model to update data…and sends a message back to the View. Note: Not showing the Model here. It is exactly the same!
  • 38. The Big Picture 05/28/10 See diagram on page 530.
  • 39. Definition: Model Contains the data, state, and application logic. State changes can occur internally or externally (by a message from the Controller) When a change of state occurs, the Model sends a notification message to the Views that want to be notified. The Model doesn’t have any direct references to the Views or Controllers that need it. 05/28/10
  • 40. Definition: View Graphic User Interface. It is the “window” to the model. View registers with the Model for notification of certain events. When notified by the Model, the View asks the Model for state information. View must have a direct reference to the Model in order to get data. (can also be an interface the Model uses) View delegates actions to the Controller. 05/28/10
  • 41. Definition: Controller Handles user actions initiated on the View. Informs the Model of any data changes. When applicable, tells the View to change it’s UI state. 05/28/10
  • 42. Lab: Part I In BeatController.start() function does three things: Sends on() message to the Model Sends DisableStartMenuItem() message to the View Sends EnableStopMenuItem() message to the View. Then we get a requirement that the end user needs to change the Mode (Basic or Advanced) at any time. If user calls start() during Basic mode, the same functionality occurs. If user calls start() during Advanced mode, the Basic mode functionality occurs, but in addition, the UI displays a video of the song. What can we do? What pattern can help us?
  • 43. Lab: Part II Let’s say we need to add permissions. Which object should be modified? (Model, View, Controller) Let’s say a change in the Model needs to result in the enabling and disabling of certain UI elements in the View. What can we do? 05/28/10
  • 44. Answer : Part I BeatController can be an abstract class with default implementation for all methods, except start (which can be marked abstract) Create two classes that inherit from BeatController (Basic and Advanced). Each class defines the unique behavior of start. Associate the View with the appropriate version of BeatController. Use Strategy Pattern to change behavior at run time. 05/28/10
  • 45. Answer: Part II Controller. We could easily create a Permission object that is accessed by the Controller. This has the benefit of keeping permission-related code out of the View. Two Answers: The View can easily respond to the change in the Model and set the appropriate UI elements; however, that is putting more business logic in the View. Controller can become an Observer of certain events in the Model (in addition to the View!). If a certain change of state occurs in the Model, the Controller can tell the View which UI elements to change. 05/28/10
  • 46. Testing Testing is a lot easier with MVC. Unit Tests can target the Controller and Model. It is harder to unit test the View. 05/28/10
  • 47. Frameworks for MVC Spring MVC Java Swing Windows Presentation Foundation (WPF) ASP.NET MVC Framework PureMVC Bistro Apache Struts And many more… 05/28/10
  • 48. Model View Presenter (MVP) Derivative of MVC. Focuses on the Presentation Layer. For example, interaction of different UI elements on a form. References http://en.wikipedia.org/wiki/Model-view-presenter http://www.mvcsharp.org/ 05/28/10
  • 49. Other Patterns Iterator Composite Builder Façade State Chain of Responsibility Flyweight Memento 05/28/10
  • 50. Iterator GoF Intent: “Provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.” There are different types of “aggregate objects” Collection ArrayList List<> Array string[] 05/28/10
  • 51. Iterator (cont) Each of these objects have different ways of looping through and accessing different elements. Iterator patterns hides the implementation of the aggregate object from the clients that access it. Advantage: You can change an ArrayList into a List<> without breaking clients that use you it. 05/28/10
  • 52. Composite GoF Intent: “allows you to compose objects into tree structures to represent whole-part hierarchies. Composite lets clients treat individual objects and composition of objects uniformly.” Think of a tree hierarchy Business objects User Interface elements (Window  Panel  Button) A Node (with Children) and a Leaf Node are all treated the same. 05/28/10
  • 53. Composite (cont) Example: Windows form where all UI elements are in a tree. Message is sent to top node to “disable all elements”. The tree is traversed and Disable message is applied to each node in the tree. Composite and Iterator are often used together. 05/28/10
  • 54. Builder Encapsulate the construction of a product and allow it to be constructed in steps. Good for the creation of complex objects. Client sends multiple messages to the Builder for creating certain parts of the structure. Then Builder returns Composite result. 05/28/10
  • 55. Facade “ Provides a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use”. Example, communication between Business and Data Layer. 05/28/10
  • 56. State Pattern GoF Intent: “Allows an object to alter its behavior when its internal state changes. The object will appear to change its class.” Strategy Pattern – behavior change due to an external change. (Remember the setBehavior() method). The Clients had to be aware of the different possible Strategies. State is basically like Strategy; however, changes occur internally. 05/28/10
  • 57. Chain of Responsibility “ Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.” Each object in chain acts as a handler. If it cannot handle the request, passes it to the next object in the chain. Often using in Windows system for handling events generated by keyboard or mouse. 05/28/10
  • 58. Flyweight GoF Intent: “Use sharing to support large numbers of fine-grained objects efficiently.” Addresses memory issues. Instead of having 100 large objects that take up memory: One stateless object Manager object that contains the state of the 100 objects Single instances will not be able to behave independently from other instances. (Probably better for read-only purposes!) 05/28/10
  • 59. Memento Be able to return object to a previous state. Handle undo. 05/28/10
  • 60. Next Steps? Read the rest of the book! Buy the Gang of Four book to get more details on the patterns mentioned in this book. Understand commonly used frameworks MVC Spring Dependency Injection 05/28/10
  • 61. Martin Fowler http://www.martinfowler.com/ Refactoring: Improving the Design of Existing Code Patterns of Enterprise Application Architecture 05/28/10

Editor's Notes

  • #2: 13 November 2008
  • #9: 5 places in DJView that would need to be modified to update the setting of BPM 13 November 2008
  • #10: Answer: Observer!! 13 November 2008
  • #11: BPM Beat 13 November 2008
  • #22: 13 November 2008
  • #26: We have a separation of View and Model. We would need to duplicate the order that things happen. For example, Constructor – CreateViews, Disable, Enable, then we initialize Model Same with Start and Stop. We send a message to the Model then set UI state. 13 November 2008
  • #27: 13 November 2008
  • #28: 13 November 2008
  • #43: 13 November 2008