470 likes | 572 Views
CSC 7322 : Object Oriented Development J Paul Gibson, A207 paul.gibson@int-edu.eu http://www-public. it-sudparis.eu /~gibson/Teaching/CSC7322/. Design Patterns …/~ gibson / Teaching /CSC7322/L5-DesignPattern-MVC.pdf. Introduction.
E N D
CSC 7322 : Object OrientedDevelopment J Paul Gibson, A207 paul.gibson@int-edu.eu http://www-public.it-sudparis.eu/~gibson/Teaching/CSC7322/ Design Patterns …/~gibson/Teaching/CSC7322/L5-DesignPattern-MVC.pdf TSP: Software Engineering
Introduction pattern noun 1 a model, guide or set of instructions for making something • a dress pattern. 2 a decorative design, often consisting of repeated motifs, eg on wallpaper or fabric. 3 a piece, eg of fabric, as a sample. 4 any excellent example suitable for imitation. 5 a coherent series of occurrences or set of features • a pattern of events. verb (patterned, patterning) (usuallypattern something on another thing) to model it on another type, design, etc. ETYMOLOGY: 14c as patron; French, from Latin patronus example or defender. SOURCE - Chambers 21st Century Dictionary TSP: Software Engineering
Introduction design verb (designed, designing) 1 to develop or prepare a plan, drawing or model of something before it is built or made. 2formal to plan, intend or develop something for a particular purpose. noun 1 a plan, drawing or model showing how something is to be made. 2 the art or job of making such drawings, plans, etc. 3 the way in which something has been made. 4 a picture, pattern, arrangement of shapes, etc used eg as decoration. 5 a plan, purpose or intention. designable adj. designedly adverb intentionally; on purpose. designingadj, derog using cunning and deceit to achieve a purpose. designingly adverb. by design intentionally. have designs on someone or something to have plans to appropriate them or it. ETYMOLOGY: 16c: from French désigner. SOURCE - Chambers 21st Century Dictionary TSP: Software Engineering
Introduction design pattern programming A description of an object-oriented design technique which names, abstracts and identifies aspects of a design structure that are useful for creating an object-oriented design. The design pattern identifies classes and instances, their roles, collaborations and responsibilities. Each design pattern focuses on a particular object-oriented design problem or issue. It describes when it applies, whether it can be applied in the presence of other design constraints, and the consequences and trade-offs of its use. Home (http://st-www.cs.uiuc.edu/users/patterns/patterns.html) ["Design Patterns: Elements of Reusable Object-Oriented Software", Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides]. (1997-07-21) SOURCE – Free On-Line Dictionary Of Computing (http://foldoc.org/) TSP: Software Engineering
Introduction • 1970’s - Christopher Alexander (an architect) worked on « Pattern Languages» whichwereapplied in manydomains: • a structured method of describing good design practices within a field of expertise. • Using a pattern language permits non-experts in a field to successfully solve very large, complex design problems. • A single problem is documented with its typical place (the syntax), and use (the grammar) with the most common and recognized good solution seen in the real world, like the entries seen in dictionaries. • Such an entry is considered to be a single design pattern; and a rich set of patterns form a language. TSP: Software Engineering
Introduction Earlyresearch: THING-MODEL-VIEW-EDITOR an Examplefrom a planning system, TrygveReenskaug, 1979. Using Pattern Languages for Object-OrientedPrograms,Kent Beck and Ward Cunningham, 1987. A Cookbook for UsingView-Controller User the Model- Interface Paradigm in Smalltalk-80, Krasner and Pope, 1988. TSP: Software Engineering
Introduction Breakthroughintomainstream: Gang of Four (GOF) Design Patterns: Abstraction and Reuse of Object-Oriented Design, Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, 1993 TSP: Software Engineering
Introduction • Furtherreading: • Design Patterns for Object-Oriented Software Development, Pree and Sikora, 1997 • The origins of pattern theory: the future of the theory, and the generation of a living world, C. Alexander, 1999 • Software Factories Assembling Applications with Patterns, Models, Frameworks and Tools, Greenfield and Short, 2003. • The Model-View-Controller (MVC) Its Past and Present, TrygveReenskaug, 2003. • What Is Web 2.0: Design Patterns and Business Models for the Next Generation of Software, O'Reilly, 2007 TSP: Software Engineering
Definitions Alexander: As an element in the world, each pattern is a relationshipbetween a certain context, a certain system of forces whichoccursrepeatedly in thatcontext, and a certain spatial configuration whichallowsthese forces to resolvethemselves. As an element of language, a pattern is an instruction, which shows how this spatial configuration canbeused, over and over again, to resolve the given system of forces, wherever the contextmakesit relevant. Each pattern describes a problemthatoccurs over and over again in ourenvironment, and thendescribes the core of the solution to thatproblem, in such a waythatyoucan use this solution a million times over, withouteverdoingit the samewaytwice. TSP: Software Engineering
Definitions • Erich Gamma (GoF): • Patterns provideyouwithtoolsthat help youwith design problems. They do so not by giving a pat solution but by explainingtrade-offs. Eventhough patterns are abstractedfromconcrete uses, theyalsoprovideyouvaluableimplementationhints. Frommy perspective itis the factthat patterns are implementablethatmakesthemsovaluable. • Patterns are distilledfrom the experiences of experts. Theyenableyou to repeat a successful design done by someoneelse. However, since patterns enablemanyimplementation variations youstill have to keep the brainturned on. • Since patterns provideyouwithnames for design building blocks theyprovideyouwith a vocabulary to describe and discuss a particular design. • I think patterns as a wholecan help people learnobject-orientedthinking: how youcanleveragepolymorphism, design for composition, delegation, balance responsibilities, and providepluggablebehavior. TSP: Software Engineering
Elements of Design Patterns • Pattern Name • Problem statement -context where it might be applied • Solution - elements of the design, their relations, responsibilities, and collaborations (including a template of the solution) • Consequences - Results and trade-offs TSP: Software Engineering
The 23 GoF patterns are generally considered the foundation for all other patterns. They are categorized in three groups: Creational, Structural, and Behavioral. TSP: Software Engineering
Design pattern composition: MVC example Traditional version of MVC as a compound pattern TSP: Software Engineering
Design pattern composition: MVC example Alternative version of MVC as a compound pattern TSP: Software Engineering
Learning by PBL • The best way to learn about patterns is to look atexamples. • Weshall do these in UML/Java, but any (OO) languagecanbeusedto model/implement/re-use a pattern. • It is best if youdiscover patterns yourself, ratherthanbeingshownthem – but thisis not guaranteed to happen! • You canalsoread about them. A good web site is: http://sourcemaking.com/design_patterns TSP: Software Engineering
The Model View Design Pattern – PBL Session Dowload the code from the module web site: …~gibson/Teaching/CSC7322/Code/DesignPattern-MVC.zip • Note the package structure – particularly the MVC components: • Models • Views • Controllers Let us examine some of this code together TSP: Software Engineering
The Model View Design Pattern – PBL Session PaddleSpecification TSP: Software Engineering
The Model View Design Pattern – PBL Session PaddleSpecification TSP: Software Engineering
The Model View Design Pattern – PBL Session PaddleSpecification /** * The lower bound on the horizontal position of the paddle */ finalintMINIMUM_position = 0; /** * The upper bound on the horizontal position of the paddle */ finalintMAXIMUM_position = 31; /** * @return true if the <code>MINIMUM_position</code> value is * less than the <code>MAXIMUM_position</code> */ booleanINVARIANT_OF_CLASS = (MINIMUM_position <= MAXIMUM_position); TSP: Software Engineering
The Model View Design Pattern – PBL Session PaddleSpecification TSP: Software Engineering
The Model View Design Pattern – PBL Session PaddleSpecification TSP: Software Engineering
The Model View Design Pattern – PBL Session PaddleSpecification TSP: Software Engineering
The Model View Design Pattern – PBL Session PaddleSpecification TSP: Software Engineering
The Model View Design Pattern – PBL Session PaddleImplementation: Paddle TSP: Software Engineering
The Model View Design Pattern – PBL Session PaddleImplementation: Paddle TO DO: Examine the code and check thatyouunderstandit. TSP: Software Engineering
The Model View Design Pattern – PBL Session PaddleImplementation: Paddle TO DO: Examine the code and check thatyouunderstandit. TSP: Software Engineering
The Model View Design Pattern – PBL Session PaddleImplementation: Paddle QUESTION: Do the methodsthat change the state respect the invariant? publicvoidupdatePosition(){ if (directionToRight && position < MAXIMUM_position) position++; elseif (!directionToRight && position > MINIMUM_position) position--; elsechangeDirection(); } publicvoidchangeDirection(){ directionToRight= ! directionToRight; } TSP: Software Engineering
The Model View Design Pattern – PBL Session PaddleImplementation: Testing the Paddle Model TSP: Software Engineering
The Model View Design Pattern – PBL Session Unit Testing the Paddle Model TO DO: Check thatyouunderstand the unit test code TSP: Software Engineering
The Model View Design Pattern – PBL Session PaddleViewSpecification Once we have testedour model (the Paddle) wecandevelop a (graphical) view: TSP: Software Engineering
The Model View Design Pattern – PBL Session PaddleViewSpecification QUESTION: Why do wespecifythesemethods? TSP: Software Engineering
The Model View Design Pattern – PBL Session PaddleView Test publicclassTest_PaddleView { publicstaticvoid main(String args[]) { PaddlepaddleModel = newPaddle(0); PaddleViewpaddleView = newPaddleView(paddleModel); paddleView.updateView(); } } TSP: Software Engineering
The Model View Design Pattern – PBL Session PaddleView – the implementation TSP: Software Engineering
The Model View Design Pattern – PBL Session PaddleView – the implementation TO DO: Check yourunderstanding of the code publicPaddleView(PaddleSpecificationrvPaddle){ frame = newJFrame("Paddle MVC"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(VIEW_WIDTH+(BORDER/2),VIEW_HEIGHT+(BORDER/2)); frame.setVisible(true); frame.setResizable(false); canvas = newPaddleViewCanvas(rvPaddle, VIEW_WIDTH, VIEW_HEIGHT); frame.getContentPane().add(canvas, BorderLayout.CENTER ); } TSP: Software Engineering
The Model View Design Pattern – PBL Session PaddleViewCanvas – where the drawingisdoneinside the View frame TO DO: Check yourunderstanding of the code TSP: Software Engineering
The Model View Design Pattern – PBL Session PaddleView – the implementation TSP: Software Engineering
The Model View Design Pattern – PBL Session Extending the model sothatitcanbeanimatedinside the view TSP: Software Engineering
The Model View Design Pattern – PBL Session Extending the model sothatitcanbeanimatedinside the view TSP: Software Engineering
The Model View Design Pattern – PBL Session Extending the model sothatitcanbeanimatedinside the view publicvoidrun(){ do{ try { Thread.sleep(DELAY); } catch (InterruptedException e) {e.printStackTrace();} updatePosition(); if (paddleView !=null) paddleView.updateView(); } while (true); } QUESTION: do youunderstand how the delayisimplemented? TSP: Software Engineering
The Model View Design Pattern – PBL Session Testing the animatedview publicclassTest_RunnableViewablePaddle { publicstaticvoid main(String args[]) { RunnableViewablePaddlervPaddle = newRunnableViewablePaddle(); PaddleViewpaddleView = newPaddleView(rvPaddle); rvPaddle.setView(paddleView); Thread paddleThread = new Thread(rvPaddle); paddleThread.run(); } } TSP: Software Engineering
The Model View Design Pattern – PBL Session Adding a controller to the system – the specification TSP: Software Engineering
The Model View Design Pattern – PBL Session Adding a controller to the system – the implementation publicclassPaddleControllerextendsPaddleControllerAbstraction{ /** * The model being controlled by the controller */ PaddleSpecificationpaddle; /** * @paramrvPaddle is the model to be controlled by the controller */ publicPaddleController(PaddleSpecificationrvPaddle){ this.paddle = rvPaddle; } /** * Change direction when a key is typed */ publicvoidkeyTyped(KeyEvent e){ paddle.changeDirection();} } TSP: Software Engineering
The Model View Design Pattern – PBL Session Adding a controller to the system – the MVC structure TSP: Software Engineering
The Model View Design Pattern – PBL Session Adding a controller to the system – the MVC structure publicPaddleMVC(){ // Construct model rvPaddle = newRunnableViewablePaddle(); // Construct view which can see model paddleView = newPaddleView(rvPaddle); //Allow the model to see view in order to make updates when state changes rvPaddle.setView(paddleView); //Constructcontroller PaddleControllerpaddleController = newPaddleController(rvPaddle); //The frame which contains the view must allow the controller to react to key presses paddleView.getFrame().addKeyListener(paddleController); } TSP: Software Engineering
The Model View Design Pattern – PBL Session Adding a controller to the system – the MVC structure Nowwejustneed a methodthatstarts a thread containing the runnableviewablepaddle publicvoidstartgame(){ Thread paddleThread = new Thread((Runnable) rvPaddle); paddleThread.run(); } TSP: Software Engineering
The Model View Design Pattern – PBL Session Adding a controller to the system – the MVC system application publicclassPaddleMVC_Application { publicstaticvoid main(String[] args){ PaddleMVC application = newPaddleMVC(); application.startgame(); } } TSP: Software Engineering
The Model View Design Pattern – PBL Session The MVC problem The use of the MVC design pattern shouldmakeiteasier to maintain/extend/update the Paddle application. TO DO: Change the model sothat the paddledoesn’tbounceitwrapsaround Change the controllersothatyou have to hold down a button to move left and hold down a button to move right Change the viewsothat the direction of the next move isrepresentedgraphically QUESTION: How manydifferentPaddlesystems are now possible (based on 2 differentmodels, twodifferentviews and 2 differentcontrollers)? Can youinstantiate all of them and test theirbehaviour? TSP: Software Engineering