Design Patterns: Prototype, State, Composite, Memento

Size: px
Start display at page:

Download "Design Patterns: Prototype, State, Composite, Memento"

Transcription

1 Design Patterns: Prototype, State, Composite, Memento Let s start by considering the CanvasEditor as we had it at the end of the last class. Recall that when a button was clicked, the button s custom ActionListener was invoked, and it set the current figure to the proper type: Outline for Lecture 16 I. The Prototype pattern II. The State pattern III. The Composite pattern IV. The Memento pattern rectbutton.addactionlistener(new ActionListener() { public void actionperformed(actionevent ae) { canvaseditor.setcurrentfigure (new Rect(0,0, 60, 40)); ); The setcurrentfigure message was received by the canvaseditor object. Let s take a look at the code for it. public class CanvasEditor implements MouseListener { private Figure currentfigure; public CanvasEditor(Figure initialfigure) { this.currentfigure = initialfigure; public void setcurrentfigure(figure newfigure) { currentfigure = newfigure; public void mouseclicked(mouseevent e) { Figure newfigure =... a new figure based on currentfigure...; ((DrawingCanvas) e.getsource()). addfigure(newfigure); Lecture 16 Object-Oriented Languages and Systems 1

2 public void mousepressed(mouseevent e) { public void mousereleased(mouseevent e) { public void mouseentered(mouseevent e) { public void mouseexited(mouseevent e) { Notice that we haven t said how to draw a new figure based on the current figure. Prototype [Skrien 8.5] How shall we draw this figure? Can we use the currentfigure object? Can we use a constructor to create it? Should we test which kind of figure that we need? if( currentfigure instanceof Ellipse ) newfigure = new Ellipse(...); else if( currentfigure instanceof Rect ) newfigure = new Rect(...); else newfigure = new Square(...); Of course not! Instead, we can just clone the current object. This makes use of Java s Cloneable interface. By implementing Cloneable, a class allows field-by-field copies to be made of its instances. This allows the Figure referred to by currentfigure to act as a prototype for the figure to be created. Here is the code. public Object clone() { CSC/ECE 517 Lecture Notes 2005, Edward F. Gehringer 2

3 try { return super.clone(); catch (CloneNotSupportedException e) { // This should never happen e.printstacktrace(); return null; Why does the method call super.clone? What class do we place this definition in? How do we use this method to create... a new figure based on currentfigure...? public void mouseclicked(mouseevent e) { Figure newfigure = (Figure) currentfigure.clone(); newfigure.setcenter(e.getx(), e.gety()); ((DrawingCanvas) e.getsource()) addfigure(newfigure); This is an instance of the Prototype pattern. Prototype Intent: Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype. Problem: Customized objects must be created, but we do not know their class or any details of how to create them. Solution: Each class that might have to create an object has a prototypical object. A creation-initiating object is invoked, and it creates objects by asking one of the prototypical objects to make a copy of itself. Lecture 16 Object-Oriented Languages and Systems 3

4 Implementation: Each class that is going to create an object must have a prototypical object. The parent class implements the Cloneable interface. Then the creation-initiating object clones itself, producing an object of the correct class. State [Skrien 8.6] We ve been talking about bad uses of case statements in programs. Another way in which case statements are sometimes used is to implement finite-state machines. There s a more o-o way to handle this situation, but before we see what it is, let s talk about an enhancement to our drawing program. So far, our application just creates figures and puts them at different places on the canvas. Once positioned, they stay in the same place forever. We d like to enhance the app to allow the figures to move. This requires adding a selection tool to the menu. When the selection tool is chosen and (a) the user clicks the mouse button inside an unselected figure, then that figure becomes the only selected figure. (b) the user clicks the mouse button inside a selected figure or outside all the figures, nothing changes. (c) the user presses the mouse inside an unselected figure and drags, then that figure becomes the only selected figure and is dragged along with the mouse. (d) the user presses the mouse inside a selected figure and drags, then that figure and all other currently selected figures are dragged with the mouse. (e) the user presses the mouse outside all figures and drags the mouse, a selection area is outlined and all figures intersecting the selection area become the selected figures. This is pretty standard behavior for drawing applications. It requires a major change to our application. CSC/ECE 517 Lecture Notes 2005, Edward F. Gehringer 4

5 Until now, we were able to ignore mouse presses, drags, and releases. However, if the selection tool is chosen, they will have to be tracked and various actions will have to be implemented. We could do this with conditionals: public void mouseclicked(mouseevent e){ if currenttool = selection { drawing.getfigurecontaining( (e.getx(), e.gety()); else { Figure newfigure = (Figure) currentfigure.clone(); newfigure.setcenter(e.getx(), e.gety()); ((DrawingCanvas) e.getsource()).addfigure (newfigure); But do we want to? What can we do instead? We can use the State pattern! State Intent: Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. Problem: A monolithic object's behavior is a function of its state, and it must change its behavior at run-time depending on that state. Or, an application is characterized by large and numerous case statements that vector flow of control based on the state of the application. Solution: Define a set of State objects. Defer the implementation of the different methods to the State objects. The client changes its state from time to time. Implementation: Define a context class to present a single interface to the outside world. Define a State abstract base class. Lecture 16 Object-Oriented Languages and Systems 5

6 Represent the different states of the state machine as derived classes of the State base class. Define state-specific behavior in the appropriate State derived classes. Maintain a pointer to the current state in the context class. To change the state of the state machine, change the current state pointer. With the State pattern, the object needing different behavior will maintain a reference to another object representing its state. Instead of having the mouseclicked method in the CanvasEditor, there are now multiple mouseclicked methods, located in the Tool classes. Here s the method in CreationTool: public void mouseclicked(mouseevent e){ Figure newfigure = (Figure) myfigure.clone(); newfigure.moveto(e.getx() - newfigure.getboundingrect().width / 2, e.gety() - newfigure.getboundingrect().height / 2); DrawingCanvas canvas = (DrawingCanvas) e.getsource(); canvas.addfigure(newfigure); canvas.unselectall(); canvas.selectfigure(newfigure); Here s the method in SelectionTool: CSC/ECE 517 Lecture Notes 2005, Edward F. Gehringer 6

7 public void mouseclicked(mouseevent e) { DrawingCanvas canvas = (DrawingCanvas) e.getsource(); Figure figure = canvas.getfigurecontaining (e.getx(), e.gety()); pressedinfigure = (figure!= null); if (pressedinfigure &&! figure.isselected()) canvas.unselectall(); if (pressedinfigure) figure.setselected(true); origin.x = e.getx(); origin.y = e.gety(); Composite [Skrien 8.7] Next, we need to allow users to group figures together to make a composite figure, which can be manipulated as a single figure. Our Drawing class stores all its figures in an ArrayList named figures. We could create a separate ArrayList for each group. That is, to implement the "Group" menu item action, we can just remove all the selected figures from figures, put those selected figures into a new ArrayList, and add that ArrayList to figures. The problem is that the Drawing class assumes that only Figure objects are in ArrayLists. So all drawing methods will have to be rewritten similarly to this: if( figures.get(i) instanceof ArrayList)...do the desired processing on the group... else...do the desired processing on the figure... Things would get worse if a group contained another group. The Composite pattern solves this. It has Lecture 16 Object-Oriented Languages and Systems 7

8 one or more leaf classes, representing individual objects, and a composite class, representing collections of objects. Both of these are subclasses of a component class. A client can refer to components without knowing whether they are composites or leaves. In our drawing program, which are the composites and which are the leaves? Here is a UML diagram: Let s take a look at a sample method, drawshape, in each of the classes. Which class is each in? public void drawshape(graphics g){ Rectangle rect = getboundingrect(); CSC/ECE 517 Lecture Notes 2005, Edward F. Gehringer 8

9 g.drawrect(rect.x, rect.y, rect.width, rect.height); public void drawshape(graphics g) { for (Iterator<Figure> it = children.iterator(); it.hasnext();) { it.next().drawshape(g); public void drawshape(graphics g) { Rectangle rect = getboundingrect(); g.drawoval(rect.x, rect.y, rect.width, rect.height); Composite Intent: Allow clients to treat individual objects and compositions of objects uniformly. Problem: The application needs to manipulate a hierarchical collection of primitive and composite objects. Primitive objects are processed one way, and composite objects are handled differently. It is inelegant to query the type of each object before processing it. Solution: Define an abstract base class (Component) that specifies the behavior that needs to be exercised uniformly across all primitive and composite objects. Make the Primitive and Composite classes subclasses of the Component class. Memento A standard feature of an editor is the ability to undo the most recent changes that the user has made. Let s add this functionality to our drawing application. We ll do this by adding an undo stack, which holds previous states of the canvas. Lecture 16 Object-Oriented Languages and Systems 9

10 The top of the stack always corresponds to the current state of the canvas. Now, what two things should we do when a change is undone? We could make the DrawingCanvas handle undoing and redoing. But this gives it a lot of extra responsibility. Is there a more elegant way? The Memento pattern solves this problem. It allows an external class to handle the states, but doesn t let this external class manipulate them in any way. Here is a description of Memento. Memento Intent: Without violating encapsulation, capture and externalize an object s internal state so that the object can be returned to this state later. Problem: We need to restore an object to its previous state. Solution: Use an Originator, which creates the Mementos (states) and a Caretaker, which performs safekeeping of the Mementos. Implementation: The client requests a Memento from the Originator when it needs to checkpoint the source object s state. The source object sets the Memento to a characterization of its state. The Caretaker preserves the Memento, but only the Originator can store and retrieve information from the Memento (the Memento is "opaque" to the client and all other objects). If the client subsequently needs to roll back the source object s state, it hands the Memento back to the Originator for reinstatement. Let s take a look at an outline of the code for the undo-redo handler. More details appear in the book. public class UndoRedoHandler { private CanvasStateStack undostack, redostack; private DrawingCanvas canvas; CSC/ECE 517 Lecture Notes 2005, Edward F. Gehringer 10

11 public UndoRedoHandler(DrawingCanvas canvas) { undostack = new CanvasStateStack(); redostack = new CanvasStateStack(); this.canvas = canvas; // Store the initial state of the canvas on // the undo stack undostack.push(canvas.creatememento());... public void undo() { if( undostack.size() == 1) return; // Only current state is on stack DrawingCanvas.State canvasstate = undostack.pop(); redostack.push(canvasstate); canvas.restorestate(undostack.peek()); public void redo() { if( redostack.isempty()) return; DrawingCanvas.State canvasstate = redostack.pop(); undostack.push(canvasstate); canvas.restorestate(canvasstate); We only need to add two methods to the DrawingCanvas class. What are they? Here is a UML sequence diagram that shows what happens when a change is undone. Lecture 16 Object-Oriented Languages and Systems 11

12 1. The ActionListener for the Undo menu item signals the UndoRedoHandler to undo. 2. The UndoRedoHandler then a. extracts the State to be restored from its undo stack and b. signals the DrawingCanvas to restore its state to that State. 3. Since the internals of the State object are private, the DrawingCanvas cannot access them, but it can ask the State object to restore the canvas s state for it. CSC/ECE 517 Lecture Notes 2005, Edward F. Gehringer 12

Design Patterns: Composite, Memento, Template Method, Decorator, Chain of Responsibility, Interpreter

Design Patterns: Composite, Memento, Template Method, Decorator, Chain of Responsibility, Interpreter Design Patterns: Composite, Memento, Template Method, Decorator, Chain of Responsibility, Interpreter Composite Outline for Week 14 [Skrien 8.7] We need to allow users to group figures together to make

More information

Design to interfaces. Favor composition over inheritance Find what varies and encapsulate it

Design to interfaces. Favor composition over inheritance Find what varies and encapsulate it Design Patterns The Gang of Four suggests a few strategies for creating good o-o designs, including Façade Design to interfaces. Favor composition over inheritance Find what varies and encapsulate it One

More information

Design Patterns: State, Bridge, Visitor

Design Patterns: State, Bridge, Visitor Design Patterns: State, Bridge, Visitor State We ve been talking about bad uses of case statements in programs. What is one example? Another way in which case statements are sometimes used is to implement

More information

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2,

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2, Java Mouse Actions C&G criteria: 5.2.1, 5.4.1, 5.4.2, 5.6.2. The events so far have depended on creating Objects and detecting when they receive the event. The position of the mouse on the screen can also

More information

Tecniche di Progettazione: Design Patterns

Tecniche di Progettazione: Design Patterns Tecniche di Progettazione: Design Patterns GoF: Memento Prototype Visitor 1 Design patterns, Laura Semini, Università di Pisa, Dipartimento di Informatica. Memento 2 Design patterns, Laura Semini, Università

More information

Tecniche di Progettazione: Design Patterns

Tecniche di Progettazione: Design Patterns Tecniche di Progettazione: Design Patterns GoF: Mediator Memento Prototype 1 Design patterns, Laura Semini, Università di Pisa, Dipartimento di Informatica. Mediator 2 Design patterns, Laura Semini, Università

More information

a correct statement? You need to know what the statement is supposed to do.

a correct statement? You need to know what the statement is supposed to do. Using assertions for correctness How can we know that software is correct? It is only correct if it does what it is supposed to do. But how do we know what it is supposed to do? We need a specification.

More information

Several patterns can be implemented elegantly using closures.

Several patterns can be implemented elegantly using closures. Closures and Patterns Several patterns can be implemented elegantly using closures. A closure is a block of code 1 that has these three properties It can be passed around as a value. It can be executed

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 35 April 15, 2013 Swing III: OO Design, Mouse InteracGon Announcements HW10: Game Project is out, due Tuesday, April 23 rd at midnight If you want

More information

The undo stack and reusing the memento pattern

The undo stack and reusing the memento pattern The undo stack and reusing the memento pattern Michaël Van Canneyt March 31, 2009 Abstract In a previous contribution, the memento pattern was introduced. In this article, the memento pattern is used in

More information

Design Patterns and Frameworks Command

Design Patterns and Frameworks Command Design Patterns and Frameworks Command Oliver Haase Oliver Haase Emfra Command 1/13 Description Classification: Object-based behavioral pattern Purpose: Encapsulate a command as an object. Allows to dynamically

More information

CSSE 220. Event Based Programming. Check out EventBasedProgramming from SVN

CSSE 220. Event Based Programming. Check out EventBasedProgramming from SVN CSSE 220 Event Based Programming Check out EventBasedProgramming from SVN Interfaces are contracts Interfaces - Review Any class that implements an interface MUST provide an implementation for all methods

More information

CSE 219 COMPUTER SCIENCE III BEHAVIORAL DESIGN PATTERNS SLIDES COURTESY: RICHARD MCKENNA, STONY BROOK UNIVERSITY

CSE 219 COMPUTER SCIENCE III BEHAVIORAL DESIGN PATTERNS SLIDES COURTESY: RICHARD MCKENNA, STONY BROOK UNIVERSITY CSE 219 COMPUTER SCIENCE III BEHAVIORAL DESIGN PATTERNS SLIDES COURTESY: RICHARD MCKENNA, STONY BROOK UNIVERSITY Behavioral Design Pattern These design patterns are specifically concerned with communication

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 35 April 21, 2014 Swing III: Paint demo, Mouse InteracFon HW 10 has a HARD deadline Announcements You must submit by midnight, April 30 th Demo your

More information

Software Engineering Prof. Rushikesh K.Joshi IIT Bombay Lecture-15 Design Patterns

Software Engineering Prof. Rushikesh K.Joshi IIT Bombay Lecture-15 Design Patterns Software Engineering Prof. Rushikesh K.Joshi IIT Bombay Lecture-15 Design Patterns Today we are going to talk about an important aspect of design that is reusability of design. How much our old design

More information

Design Patterns: Template Method, Strategy, State, Bridge

Design Patterns: Template Method, Strategy, State, Bridge Design Patterns: Template Method, Strategy, State, Bridge [HFDP, Ch. 8] Say we have two classes whose code looks similar, but isn t identical. We can duplicate the code, but change it where changes are

More information

Software Construction

Software Construction Lecture 11: Command Design Pattern Software Construction in Java for HSE Moscow Tom Verhoeff Eindhoven University of Technology Department of Mathematics & Computer Science Software Engineering & Technology

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 36 November 30, 2018 Mushroom of Doom Model / View / Controller Chapter 31 Announcements Game Project Complete Code Due: Monday, December 10th NO LATE

More information

Factory Method. Comp435 Object-Oriented Design. Factory Method. Factory Method. Factory Method. Factory Method. Computer Science PSU HBG.

Factory Method. Comp435 Object-Oriented Design. Factory Method. Factory Method. Factory Method. Factory Method. Computer Science PSU HBG. Comp435 Object-Oriented Design Week 11 Computer Science PSU HBG 1 Define an interface for creating an object Let subclasses decide which class to instantiate Defer instantiation to subclasses Avoid the

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

COMP 102: Test 2 Model Solutions

COMP 102: Test 2 Model Solutions Family Name:.......................... Other Names:.......................... ID Number:............................ Instructions Time allowed: 45 minutes There are 45 marks in total. Answer all the questions.

More information

Chapter 1 GUI Applications

Chapter 1 GUI Applications Chapter 1 GUI Applications 1. GUI Applications So far we've seen GUI programs only in the context of Applets. But we can have GUI applications too. A GUI application will not have any of the security limitations

More information

The AWT Event Model 9

The AWT Event Model 9 The AWT Event Model 9 Course Map This module covers the event-based GUI user input mechanism. Getting Started The Java Programming Language Basics Identifiers, Keywords, and Types Expressions and Flow

More information

Dartmouth College Computer Science 10, Fall 2015 Midterm Exam

Dartmouth College Computer Science 10, Fall 2015 Midterm Exam Dartmouth College Computer Science 10, Fall 2015 Midterm Exam 6.00-9.00pm, Monday, October 19, 2015 105 Dartmouth Hall Professor Prasad Jayanti Print your name: Print your section leader name: If you need

More information

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011 GUI DYNAMICS Lecture July 26 CS2110 Summer 2011 GUI Statics and GUI Dynamics 2 Statics: what s drawn on the screen Components buttons, labels, lists, sliders, menus,... Containers: components that contain

More information

CS 106A, Lecture 14 Events and Instance Variables

CS 106A, Lecture 14 Events and Instance Variables CS 106A, Lecture 14 Events and Instance Variables Reading: Art & Science of Java, Ch. 10.1-10.4 This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons

More information

2.1 Introduction UML Preliminaries Class diagrams Modelling delegation... 4

2.1 Introduction UML Preliminaries Class diagrams Modelling delegation... 4 Department of Computer Science COS121 Lecture Notes Chapter 2- Memento design pattern Copyright c 2015 by Linda Marshall and Vreda Pieterse. All rights reserved. Contents 2.1 Introduction.................................

More information

CS 349 / SE 382 Design Patterns. Professor Michael Terry January 21, 2009

CS 349 / SE 382 Design Patterns. Professor Michael Terry January 21, 2009 CS 349 / SE 382 Design Patterns Professor Michael Terry January 21, 2009 Today s Agenda More demos! Design patterns CS 349 / SE 382 / 2 Announcements Assignment 1 due Monday at 5PM! CS 349 / SE 382 / 3

More information

Topic Notes: Java and Objectdraw Basics

Topic Notes: Java and Objectdraw Basics Computer Science 120 Introduction to Programming Siena College Spring 2011 Topic Notes: Java and Objectdraw Basics Event-Driven Programming in Java A program expresses an algorithm in a form understandable

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 34 April 13, 2017 Model / View / Controller Chapter 31 How is the Game Project going so far? 1. not started 2. got an idea 3. submitted design proposal

More information

EPL 603 TOPICS IN SOFTWARE ENGINEERING. Lab 6: Design Patterns

EPL 603 TOPICS IN SOFTWARE ENGINEERING. Lab 6: Design Patterns EPL 603 TOPICS IN SOFTWARE ENGINEERING Lab 6: Design Patterns Links to Design Pattern Material 1 http://www.oodesign.com/ http://www.vincehuston.org/dp/patterns_quiz.html Types of Design Patterns 2 Creational

More information

public Candy() { ingredients = new ArrayList<String>(); ingredients.add("sugar");

public Candy() { ingredients = new ArrayList<String>(); ingredients.add(sugar); Cloning Just like the name implies, cloning is making a copy of something. To be true to the nature of cloning, it should be an exact copy. While this can be very useful, it is not always necessary. For

More information

Readability [Skrien 4.0] Programs must be written for people to read, and only incidentally for machines to execute.

Readability [Skrien 4.0] Programs must be written for people to read, and only incidentally for machines to execute. Readability [Skrien 4.0] Programs must be written for people to read, and only incidentally for machines to execute. Abelson & Sussman Use a good set of coding conventions, such as the ones given in the

More information

Introduction to Software Engineering: Object Design I Reuse & Patterns

Introduction to Software Engineering: Object Design I Reuse & Patterns Introduction to Software Engineering: Object Design I Reuse & Patterns John T. Bell Department of Computer Science University of Illinois, Chicago Based on materials from Bruegge & DuToit 3e, Chapter 8,

More information

Lecture 5: Java Graphics

Lecture 5: Java Graphics Lecture 5: Java Graphics CS 62 Spring 2019 William Devanny & Alexandra Papoutsaki 1 New Unit Overview Graphical User Interfaces (GUI) Components, e.g., JButton, JTextField, JSlider, JChooser, Containers,

More information

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread G51PGP Programming Paradigms Lecture 008 Inner classes, anonymous classes, Swing worker thread 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals

More information

the gamedesigninitiative at cornell university Lecture 12 Component Design

the gamedesigninitiative at cornell university Lecture 12 Component Design Lecture 12 Component Design Recall: Problem with Subclassing Games have lots of classes Each game entity is different Needs its own functionality (e.g. object methods) NPC Want to avoid redundancies Makes

More information

Design Patterns. Manuel Mastrofini. Systems Engineering and Web Services. University of Rome Tor Vergata June 2011

Design Patterns. Manuel Mastrofini. Systems Engineering and Web Services. University of Rome Tor Vergata June 2011 Design Patterns Lecture 2 Manuel Mastrofini Systems Engineering and Web Services University of Rome Tor Vergata June 2011 Structural patterns Part 2 Decorator Intent: It attaches additional responsibilities

More information

UI Software Organization

UI Software Organization UI Software Organization The user interface From previous class: Generally want to think of the UI as only one component of the system Deals with the user Separate from the functional core (AKA, the app

More information

CS 106A, Lecture 14 Events and Instance Variables

CS 106A, Lecture 14 Events and Instance Variables CS 106A, Lecture 14 Events and Instance Variables Reading: Art & Science of Java, Ch. 10.1-10.4 This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons

More information

SDC Design patterns GoF

SDC Design patterns GoF SDC Design patterns GoF Design Patterns The design pattern concept can be viewed as an abstraction of imitating useful parts of other software products. The design pattern is a description of communicating

More information

Graphical User Interfaces 2

Graphical User Interfaces 2 Graphical User Interfaces 2 CSCI 136: Fundamentals CSCI 136: Fundamentals of Computer of Science Computer II Science Keith II Vertanen Keith Vertanen Copyright 2011 Extending JFrame Dialog boxes Overview

More information

User interfaces and Swing

User interfaces and Swing User interfaces and Swing Overview, applets, drawing, action listening, layout managers. APIs: java.awt.*, javax.swing.*, classes names start with a J. Java Lectures 1 2 Applets public class Simple extends

More information

EINDHOVEN UNIVERSITY OF TECHNOLOGY

EINDHOVEN UNIVERSITY OF TECHNOLOGY EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics & Computer Science Exam Programming Methods, 2IP15, Wednesday 17 April 2013, 09:00 12:00 TU/e THIS IS THE EXAMINER S COPY WITH (POSSIBLY INCOMPLETE)

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 35 November 30 th 2015 Design PaBerns Model / View / Controller Chapter 31 Game project grading Game Design Proposal Milestone Due: (12 points) Tuesday

More information

Object Oriented Programming. What is this Object? Using the Object s Slots

Object Oriented Programming. What is this Object? Using the Object s Slots 1 Object Oriented Programming Chapter 2 introduces Object Oriented Programming. OOP is a relatively new approach to programming which supports the creation of new data types and operations to manipulate

More information

Object-Oriented Oriented Programming

Object-Oriented Oriented Programming Object-Oriented Oriented Programming Composite Pattern CSIE Department, NTUT Woei-Kae Chen Catalog of Design patterns Creational patterns Abstract Factory, Builder, Factory Method, Prototype, Singleton

More information

Think of drawing/diagramming editors. ECE450 Software Engineering II. The problem. The Composite pattern

Think of drawing/diagramming editors. ECE450 Software Engineering II. The problem. The Composite pattern Think of drawing/diagramming editors ECE450 Software Engineering II Drawing/diagramming editors let users build complex diagrams out of simple components The user can group components to form larger components......which

More information

UCLA PIC 20A Java Programming

UCLA PIC 20A Java Programming UCLA PIC 20A Java Programming Instructor: Ivo Dinov, Asst. Prof. In Statistics, Neurology and Program in Computing Teaching Assistant: Yon Seo Kim, PIC University of California, Los Angeles, Summer 2002

More information

Java for Interfaces and Networks (DT3010, HT10)

Java for Interfaces and Networks (DT3010, HT10) Java for Interfaces and Networks (DT3010, HT10) Mouse Events, Timers, Serialization Federico Pecora School of Science and Technology Örebro University federico.pecora@oru.se Federico Pecora Java for Interfaces

More information

Android Tutorials. RCH 1:30 (120) MC 3:30 (66) Note: Good advice is to try the RCH session, as the MC 4060 room is small

Android Tutorials. RCH 1:30 (120) MC 3:30 (66) Note: Good advice is to try the RCH session, as the MC 4060 room is small Android Tutorials RCH 207 @ 1:30 (120) MC 4060 @ 3:30 (66) Note: Good advice is to try the RCH session, as the MC 4060 room is small Undo 2 Most Basic Undo Manual undo without programmer Consider a video

More information

HW#1: Pencil Me In Status!? How was Homework #1? Reminder: Handouts. Homework #2: Java Draw Demo. 3 Handout for today! Lecture-Homework mapping.

HW#1: Pencil Me In Status!? How was Homework #1? Reminder: Handouts. Homework #2: Java Draw Demo. 3 Handout for today! Lecture-Homework mapping. HW#1: Pencil Me In Status!? CS193J: Programming in Java Summer Quarter 2003 Lecture 6 Inner Classes, Listeners, Repaint Manu Kumar sneaker@stanford.edu How was Homework #1? Comments please? SITN students

More information

Abstract Classes and Interfaces

Abstract Classes and Interfaces Abstract Classes and Interfaces Reading: Reges and Stepp: 9.5 9.6 CSC216: Programming Concepts Sarah Heckman 1 Abstract Classes A Java class that cannot be instantiated, but instead serves as a superclass

More information

EXAMINATIONS 2010 END-OF-YEAR COMP 102 INTRODUCTION TO COMPUTER PROGRAM DESIGN

EXAMINATIONS 2010 END-OF-YEAR COMP 102 INTRODUCTION TO COMPUTER PROGRAM DESIGN T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:....................... EXAMINATIONS 2010 END-OF-YEAR COMP 102 INTRODUCTION TO

More information

Component-Based Behavioural Modelling with High-Level Petri Nets

Component-Based Behavioural Modelling with High-Level Petri Nets Component-Based Behavioural Modelling with High-Level Petri Nets Rémi Bastide, Eric Barboni LIIHS IRIT, University of Toulouse, France {bastide, barboni}@irit.fr Software Components Active domain for industry,

More information

Software Design Patterns. Aliaksei Syrel

Software Design Patterns. Aliaksei Syrel Software Design Patterns Aliaksei Syrel 1 Pattern types Creational Patterns Behavioural Patterns Structural Patterns 2 Creational Patterns Creational design patterns deal with object creation mechanisms,

More information

Events Chris Piech CS106A, Stanford University. Piech, CS106A, Stanford University

Events Chris Piech CS106A, Stanford University. Piech, CS106A, Stanford University Events Chris Piech CS106A, Stanford University Catch Me If You Can We ve Gotten Ahead of Ourselves Source: The Hobbit Start at the Beginning Source: The Hobbit Learning Goals 1. Write a program that can

More information

Design Patterns. Paul Jackson. School of Informatics University of Edinburgh

Design Patterns. Paul Jackson. School of Informatics University of Edinburgh Design Patterns Paul Jackson School of Informatics University of Edinburgh Design Patterns Reuse of good ideas A pattern is a named, well understood good solution to a common problem. Experienced designers

More information

Lecture 3: Java Graphics & Events

Lecture 3: Java Graphics & Events Lecture 3: Java Graphics & Events CS 62 Fall 2017 Kim Bruce & Alexandra Papoutsaki Text Input Scanner class Constructor: myscanner = new Scanner(System.in); can use file instead of System.in new Scanner(new

More information

2.1 Design Patterns and Architecture (continued)

2.1 Design Patterns and Architecture (continued) MBSE - 2.1 Design Patterns and Architecture 1 2.1 Design Patterns and Architecture (continued) 1. Introduction 2. Model Construction 2.1 Design Patterns and Architecture 2.2 State Machines 2.3 Timed Automata

More information

2.1 Design Patterns and Architecture (continued)

2.1 Design Patterns and Architecture (continued) MBSE - 2.1 Design Patterns and Architecture 1 2.1 Design Patterns and Architecture (continued) 1. Introduction 2. Model Construction 2.1 Design Patterns and Architecture 2.2 State Machines 2.3 Abstract

More information

ECE 462 Object-Oriented Programming using C++ and Java. Key Inputs in Java Games

ECE 462 Object-Oriented Programming using C++ and Java. Key Inputs in Java Games ECE 462 Object-Oriented Programming g using C++ and Java Key Inputs in Java Games Yung-Hsiang Lu yunglu@purdue.edu d YHL Java Key Input 1 Handle Key Events have the focus of the keyboard inputs by calling

More information

CS1004: Intro to CS in Java, Spring 2005

CS1004: Intro to CS in Java, Spring 2005 CS1004: Intro to CS in Java, Spring 2005 Lecture #13: Java OO cont d. Janak J Parekh janak@cs.columbia.edu Administrivia Homework due next week Problem #2 revisited Constructors, revisited Remember: a

More information

Design Patterns. (and anti-patterns)

Design Patterns. (and anti-patterns) Design Patterns (and anti-patterns) Design Patterns The Gang of Four defined the most common object-oriented patterns used in software. These are only the named ones Lots more variations exist Design Patterns

More information

Windows and Events. created originally by Brian Bailey

Windows and Events. created originally by Brian Bailey Windows and Events created originally by Brian Bailey Announcements Review next time Midterm next Friday UI Architecture Applications UI Builders and Runtimes Frameworks Toolkits Windowing System Operating

More information

Graphical User Interfaces 2

Graphical User Interfaces 2 Graphical User Interfaces 2 CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2014 2011 Extending JFrame Dialog boxes Overview Ge

More information

Cheng, CSE870. More Frameworks. Overview. Recap on OOP. Acknowledgements:

Cheng, CSE870. More Frameworks. Overview. Recap on OOP. Acknowledgements: More Frameworks Acknowledgements: K. Stirewalt. Johnson, B. Foote Johnson, Fayad, Schmidt Overview eview of object-oriented programming (OOP) principles. Intro to OO frameworks: o Key characteristics.

More information

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created. + Inheritance + Inheritance Classes that we design in Java can be used to model some concept in our program. For example: Pokemon a = new Pokemon(); Pokemon b = new Pokemon() Sometimes we need to create

More information

Topics in Object-Oriented Design Patterns

Topics in Object-Oriented Design Patterns Software design Topics in Object-Oriented Design Patterns Material mainly from the book Design Patterns by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides; slides originally by Spiros Mancoridis;

More information

I/O Framework and Case Study. CS151 Chris Pollett Nov. 2, 2005.

I/O Framework and Case Study. CS151 Chris Pollett Nov. 2, 2005. I/O Framework and Case Study CS151 Chris Pollett Nov. 2, 2005. Outline Character Streams Random Access Files Design case study Planning Iterations Character Streams Java internally represents strings as

More information

AP CS Unit 12: Drawing and Mouse Events

AP CS Unit 12: Drawing and Mouse Events AP CS Unit 12: Drawing and Mouse Events A JPanel object can be used as a container for other objects. It can also be used as an object that we can draw on. The first example demonstrates how to do that.

More information

EE219 Object Oriented Programming I (2005/2006) SEMESTER 1 SOLUTIONS

EE219 Object Oriented Programming I (2005/2006) SEMESTER 1 SOLUTIONS Q1(a) Corrected code is: EE219 Object Oriented Programming I (2005/2006) SEMESTER 1 SOLUTIONS 01 #include 02 using namespace std; 03 04 class Question1 05 06 int a,b,*p; 07 08 public: 09 Question1(int

More information

COMP19612 exam performance feedback 2014

COMP19612 exam performance feedback 2014 COMP19612 exam performance feedback 2014 (excluding section A which is multiple choice) Questions in plain font, original marking scheme in bold, additional comments in bold italic. Question 1 The students

More information

2IS45 Programming

2IS45 Programming Course Website Assignment Goals 2IS45 Programming http://www.win.tue.nl/~wsinswan/programmeren_2is45/ Rectangles Learn to use existing Abstract Data Types based on their contract (class Rectangle in Rectangle.

More information

Design Pa*erns. + Anima/on Undo/Redo Graphics and Hints

Design Pa*erns. + Anima/on Undo/Redo Graphics and Hints Design Pa*erns + Anima/on Undo/Redo Graphics and Hints Design Pa*erns Design: the planning that lays the basis for the making of every object or system Pa*ern: a type of theme of recurring events or objects

More information

Learning from Bad Examples. CSCI 5828: Foundations of Software Engineering Lecture 25 11/18/2014

Learning from Bad Examples. CSCI 5828: Foundations of Software Engineering Lecture 25 11/18/2014 Learning from Bad Examples CSCI 5828: Foundations of Software Engineering Lecture 25 11/18/2014 1 Goals Demonstrate techniques to design for shared mutability Build on an example where multiple threads

More information

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics Topic 9: Swing Outline Swing = Java's GUI library Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 7: Expand moving shapes from Assignment 4 into game. "Programming

More information

CSCD01 Engineering Large Software Systems. Design Patterns. Joe Bettridge. Winter With thanks to Anya Tafliovich

CSCD01 Engineering Large Software Systems. Design Patterns. Joe Bettridge. Winter With thanks to Anya Tafliovich CSCD01 Engineering Large Software Systems Design Patterns Joe Bettridge Winter 2018 With thanks to Anya Tafliovich Design Patterns Design patterns take the problems consistently found in software, and

More information

H212 Introduction to Software Systems Honors

H212 Introduction to Software Systems Honors Introduction to Software Systems Honors Lecture #15: October 21, 2015 1/34 Generic classes and types Generic programming is the creation of programming constructs that can be usedwith many different types.

More information

Object-Oriented Concepts and Design Principles

Object-Oriented Concepts and Design Principles Object-Oriented Concepts and Design Principles Signature Specifying an object operation or method involves declaring its name, the objects it takes as parameters and its return value. Known as an operation

More information

Reviewing OO Concepts

Reviewing OO Concepts Reviewing OO Concepts Users want to draw circles onto the display canvas. public class Circle { // more code here SWEN-261 Introduction to Software Engineering Department of Software Engineering Rochester

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 43 Dynamic Binding (Polymorphism): Part III Welcome to Module

More information

Software Design: Copy & Paste

Software Design: Copy & Paste Software Design: Copy & Paste Your assistant for this week Velko Vechev E-mail: velko.vechev@inf.ethz.ch Office: CNB H 100.9 You can simply stop by. You can also drop me a short e-mail to check if I m

More information

Programmierpraktikum

Programmierpraktikum Programmierpraktikum Claudius Gros, SS2012 Institut für theoretische Physik Goethe-University Frankfurt a.m. 1 of 18 17/01/13 11:46 Java Applets 2 of 18 17/01/13 11:46 Java applets embedding Java applications

More information

Exercise 12 Initialization December 16, 2016

Exercise 12 Initialization December 16, 2016 Concepts of Object-Oriented Programming AS 2016 Exercise 12 Initialization December 16, 2016 Task 1 Consider a Java class Vector, representing a 2 dimensional vector: public class Vector { public Number!

More information

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Lecture 36: Cloning Last time: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Today: 1. Project #7 assigned 2. equals reconsidered 3. Copying and cloning 4. Composition 11/27/2006

More information

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing CSEN401 Computer Programming Lab Topics: Graphical User Interface Window Interfaces using Swing Prof. Dr. Slim Abdennadher 22.3.2015 c S. Abdennadher 1 Swing c S. Abdennadher 2 AWT versus Swing Two basic

More information

GUI 4.1 GUI GUI MouseTest.java import javax.swing.*; import java.awt.*; import java.awt.event.*; /* 1 */

GUI 4.1 GUI GUI MouseTest.java import javax.swing.*; import java.awt.*; import java.awt.event.*; /* 1 */ 25 4 GUI GUI GUI 4.1 4.1.1 MouseTest.java /* 1 */ public class MouseTest extends JApplet implements MouseListener /* 2 */ { int x=50, y=20; addmouselistener(this); /* 3 */ super.paint(g); /* 4 */ g.drawstring("hello

More information

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections Thread Safety Today o Confinement o Threadsafe datatypes Required reading Concurrency Wrapper Collections Optional reading The material in this lecture and the next lecture is inspired by an excellent

More information

Design Patterns. Comp2110 Software Design. Department of Computer Science Australian National University. Second Semester

Design Patterns. Comp2110 Software Design. Department of Computer Science Australian National University. Second Semester Design Patterns Comp2110 Software Design Department of Computer Science Australian National University Second Semester 2005 1 Design Pattern Space Creational patterns Deal with initializing and configuring

More information

Classes, interfaces, & documentation. Review of basic building blocks

Classes, interfaces, & documentation. Review of basic building blocks Classes, interfaces, & documentation Review of basic building blocks Objects Data structures literally, storage containers for data constitute object knowledge or state Operations an object can perform

More information

CISC 1600, Lab 3.1: Processing

CISC 1600, Lab 3.1: Processing CISC 1600, Lab 3.1: Processing Prof Michael Mandel 1 Getting set up For this lab, we will be using OpenProcessing, a site for building processing sketches online using processing.js. 1.1. Go to https://www.openprocessing.org/class/57767/

More information

Drawing in 3D (viewing, projection, and the rest of the pipeline)

Drawing in 3D (viewing, projection, and the rest of the pipeline) Drawing in 3D (viewing, projection, and the rest of the pipeline) CS559 Spring 2016 Lecture 6 February 11, 2016 The first 4 Key Ideas 1. Work in convenient coordinate systems. Use transformations to get

More information

Objects and Iterators

Objects and Iterators Objects and Iterators Can We Have Data Structures With Generic Types? What s in a Bag? All our implementations of collections so far allowed for one data type for the entire collection To accommodate a

More information

Logistics. Final Exam on Friday at 3pm in CHEM 102

Logistics. Final Exam on Friday at 3pm in CHEM 102 Java Review Logistics Final Exam on Friday at 3pm in CHEM 102 What is a class? A class is primarily a description of objects, or instances, of that class A class contains one or more constructors to create

More information

Parallel access to linked data structures

Parallel access to linked data structures Parallel access to linked data structures [Solihin Ch. 5] Answer the questions below. Name some linked data structures. What operations can be performed on all of these structures? Why is it hard to parallelize

More information

The Strategy Pattern Design Principle: Design Principle: Design Principle:

The Strategy Pattern Design Principle: Design Principle: Design Principle: Strategy Pattern The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Design

More information

Programming Languages 2nd edition Tucker and Noonan"

Programming Languages 2nd edition Tucker and Noonan Programming Languages 2nd edition Tucker and Noonan" Chapter 16 Event-Driven Programming Of all men s miseries the bitterest is this, to know so much and to have control over nothing." " " " " " " "Herodotus

More information

Appendix G Navigation and Collision Detection for Web-Based 3D Experiment

Appendix G Navigation and Collision Detection for Web-Based 3D Experiment Appendix G Appendix G Navigation and Collision Detection for Web-Based 3D Experiment G.1 ImportInG libraries import javax.media.j3d.*; import javax.vecmath.*; import java.awt.event.*; import java.awt.awtevent;

More information

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017 Inheritance Lecture 11 COP 3252 Summer 2017 May 25, 2017 Subclasses and Superclasses Inheritance is a technique that allows one class to be derived from another. A derived class inherits all of the data

More information