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

Similar documents
SDC Design patterns GoF

Design Pattern. CMPSC 487 Lecture 10 Topics: Design Patterns: Elements of Reusable Object-Oriented Software (Gamma, et al.)

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

Ingegneria del Software Corso di Laurea in Informatica per il Management. Design Patterns part 1

Introduction to Software Engineering: Object Design I Reuse & Patterns

Trusted Components. Reuse, Contracts and Patterns. Prof. Dr. Bertrand Meyer Dr. Karine Arnout

Produced by. Design Patterns. MSc in Communications Software. Eamonn de Leastar

Object-oriented Software Design Patterns

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

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

Design patterns. Jef De Smedt Beta VZW

DESIGN PATTERN - INTERVIEW QUESTIONS

TDDB84. Lecture 2. fredag 6 september 13

Object-Oriented Oriented Programming

UNIT I Introduction to Design Patterns

Prototyping a Swing Interface with the Netbeans IDE GUI Editor

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

Pro Objective-C Design Patterns for ios

Using Design Patterns in Java Application Development

Tuesday, October 4. Announcements

CSE 70 Final Exam Fall 2009

Programming Language Concepts: Lecture 8

What is Design Patterns?

SYLLABUS CHAPTER - 1 [SOFTWARE REUSE SUCCESS FACTORS] Reuse Driven Software Engineering is a Business

UNIT I Introduction to Design Patterns

Behavioral Design Patterns. CSE260, Computer Science B: Honors Stony Brook University

Design Patterns Reid Holmes

OODP Session 4. Web Page: Visiting Hours: Tuesday 17:00 to 19:00

Ownership in Design Patterns. Master's Thesis Final Presentation Stefan Nägeli

CS560. Lecture: Design Patterns II Includes slides by E. Gamma et al., 1995

Ingegneria del Software Corso di Laurea in Informatica per il Management. Design Patterns part 1

Design Patterns. SE3A04 Tutorial. Jason Jaskolka

Creational Design Patterns

A few important patterns and their connections

Plan. A few important patterns and their connections. Singleton. Singleton: class diagram. Singleton Factory method Facade

Socket attaches to a Ratchet. 2) Bridge Decouple an abstraction from its implementation so that the two can vary independently.

Patterns. Erich Gamma Richard Helm Ralph Johnson John Vlissides

The Design Patterns Matrix From Analysis to Implementation

CSCI 253. Overview. The Elements of a Design Pattern. George Blankenship 1. Object Oriented Design: Template Method Pattern. George Blankenship

Software Design COSC 4353/6353 D R. R A J S I N G H

COSC 3351 Software Design. Design Patterns Behavioral Patterns (I)

A Reconnaissance on Design Patterns

Design Pattern and Software Architecture: IV. Design Pattern

CSCI Object Oriented Design: Frameworks and Design Patterns George Blankenship. Frameworks and Design George Blankenship 1

Topics in Object-Oriented Design Patterns

Design Patterns. Observations. Electrical Engineering Patterns. Mechanical Engineering Patterns

Object Oriented Methods with UML. Introduction to Design Patterns- Lecture 8

Design Pattern What is a Design Pattern? Design Pattern Elements. Almas Ansari Page 1

Design Patterns. (and anti-patterns)

Software Development Project. Kazi Masudul Alam

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

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

Slide 1. Design Patterns. Prof. Mirco Tribastone, Ph.D

Design Patterns: Structural and Behavioural

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

design patterns FOR B.tech (jntu - hyderabad & kakinada) (IV/I - CSE AND IV/II - IT) CONTENTS 1.1 INTRODUCTION TO DESIGN PATTERNS TTERNS... TTERN?...

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

MVC. Model-View-Controller. Design Patterns. Certain programs reuse the same basic structure or set of ideas

Information systems modelling UML and service description languages

Widgets. Widgets Widget Toolkits. User Interface Widget

Top Down Design vs. Modularization

C++ for System Developers with Design Pattern

Design Patterns. Dr. Rania Khairy. Software Engineering and Development Tool

Software Quality Management

Lecture 17: Patterns Potpourri. Copyright W. Howden 1

1 Software Architecture

Software Design Patterns. Aliaksei Syrel

CSC207H: Software Design Lecture 6

Design Patterns. An introduction

Modellistica Medica. Maria Grazia Pia, INFN Genova. Scuola di Specializzazione in Fisica Sanitaria Genova Anno Accademico

INSTITUTE OF AERONAUTICAL ENGINEERING

What is Design Patterns?

Writing your own Java I/O Decorator p. 102 Tools for your Design Toolbox p. 105 Exercise Solutions p. 106 The Factory Pattern Baking with OO

Outline. More on the Swing API Graphics: double buffering and timers Model - View - Controller paradigm Applets

CSE 331 Final Exam 3/12/12

Software Eningeering. Lecture 9 Design Patterns 2

A Rapid Overview of UML

What is a Pattern? Lecture 40: Design Patterns. Elements of Design Patterns. What are design patterns?

Design Patterns Lecture 2

Design Patterns: Prototype, State, Composite, Memento

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

Object-Oriented Design

Applying Design Patterns to SCA Implementations

I, J. Key-value observing (KVO), Label component, 32 text property, 39

Object Oriented Paradigm

SWEN425 DESIGN PATTERNS

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

CSCI 253. Overview. The Elements of a Design Pattern. George Blankenship 1. Object Oriented Design: Iterator Pattern George Blankenship

UP Requirements. Software Design - Dr Eitan Hadar (c) Activities of greater emphasis in this book. UP Workflows. Business Modeling.

» Access elements of a container sequentially without exposing the underlying representation

Widgets. Overview. Widget. Widgets Widget toolkits Lightweight vs. heavyweight widgets Swing Widget Demo

Applying Design Patterns to accelerate development of reusable, configurable and portable UVCs. Accellera Systems Initiative 1

Lectures 24 and 25 Introduction to Architectural Styles and Design Patterns

Original GUIs. IntroGUI 1

Java Programming Lecture 6

Composite Pattern. IV.4 Structural Pattern

be used for more than one use case (for instance, for use cases Create User and Delete User, one can have one UserController, instead of two separate

CS251 Software Engineering Lectures 18: Intro to DP

Application Architectures, Design Patterns

administrivia today UML start design patterns Tuesday, September 28, 2010

Transcription:

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 between objects. Increase flexibility in carrying out communication between objects. https://www.youtube.com/watch?v=kitdr0yoiqa

Common Design Patterns Creational Structural Behavioral Factory Singleton Builder Prototype Decorator Adapter Facade Flyweight Component Architecture Strategy Template Observer Command Iterator State Textbook: Head First Design Patterns

The Strategy Pattern How does it work? defines a family of algorithms, encapsulates each one, and makes them interchangeable lets the algorithm vary independently from the clients that use them An algorithm in a box place essential steps for an algorithm in a strategy interface different methods represent different parts of the algorithm classes implementing this interface customize methods Classes can be composed (HAS-A) of the interface type the interface type is the apparent type the actual type can be determined at run-time

Example https://www.youtube.com/watch?v=qkel46jodu4

Common Design Patterns Creational Structural Behavioral Factory Singleton Builder Prototype Decorator Adapter Facade Flyweight Component Architecture Strategy Template Observer Command Iterator State Textbook: Head First Design Patterns

Template Method Pattern Defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Lets subclasses redefine certain steps of an algorithm without changing the algorithm s structure. A template for an algorithm https://www.youtube.com/watch?v=bpvdekl1z0o

Template Method Pattern

Template Method Pattern

What s a hook? A type of method Declared in the abstract class only given an empty or default implementation Gives subclasses the ability to hook into the algorithm at various points, if they wish a subclass is also free to ignore the hook.

Example

What s the difference? Strategy vs. Template Method Strategy subclasses decide how to implement steps in an algorithm Template Method encapsulate interchangeable behaviors and use delegation to decide which behavior to use

Common Design Patterns Creational Structural Behavioral Factory Singleton Builder Prototype Decorator Adapter Facade Flyweight Component Architecture Strategy Template Observer Command Iterator State Textbook: Head First Design Patterns

The Observer Pattern Defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically. Hmm, where have we seen this? in our GUI State Manager class maintains application's state call methods to change app's state app's state change forces update of GUI https://www.youtube.com/watch?v=hb2iv-ujfjs

TableView Used to display spreadsheets and tables How is the table data stored? in an ObservableList we call this the table s data model

Editing the table To edit the table, you must go through the model: TableView table = new TableView( ObservableList<DataPrototype> model = table.getitems(); // Add Data model.add( // Remove Data model.remove( // Change Data DataPrototype data = model.get( data.set( // UPDATING THE MODEL (ObservableList) AND/OR THE DATA (DataPrototype) // WILL AUTOMATICALLY UPDATE THE VIEW (TableView) THANKS TO MVC!

Complex Controls have their own States Tables, trees, lists, combo boxes, etc. data is managed separately from the view when state changes, view is updated This is called MVC Model View Controller MVC employs the Observer Pattern

MVC employs the Observer Pattern Model data structure, no visual representation notifies views when something interesting happens View visual representation views attach themselves to model in order to be notified Controller event handler listeners that are attached to view in order to be notified of user interaction (or otherwise) MVC Interaction controller updates model model tells view that data has changed view redrawn

Controller Model View update (add, etc.) notify repaint return return

MVC Architecture Model The model passes its data to the view for rendering View The controller updates the model based on events received Controller The view determines which events are passed to the controller

Example https://www.tutorialspoint.com/design_pattern/observer_pattern.htm

Common Design Patterns Creational Structural Behavioral Factory Singleton Builder Prototype Decorator Adapter Facade Flyweight Component Architecture Strategy Template Observer Command Iterator State Textbook: Head First Design Patterns

Command Abstraction For many GUIs, a single function may be triggered by many means (e.g., keystroke, menu, button, etc ) we want to link all similar events to the same listener The information concerning the command can be abstracted to a separate command object Common Approach: specify a String for each command have listener respond to each command differently ensure commands are handled in a uniform way commands can be specified inside a text file The Command Pattern https://www.youtube.com/watch?v=inkvqmiptmy

Suppose I wanted to create a simple GUI: 1 colored panel 2 buttons, yellow & red 2 menu items, yellow & red clicking on the buttons or menu items changes the color of the panel Since the buttons & the menu items both perform the same function, they should be tied to the same commands I could even add popup menu items Example

Using Command Strings public class ColorCommandFrame1 extends JFrame implements ActionListener { private Toolkit tk = Toolkit.getDefaultToolkit(); private ImageIcon yellowicon = new ImageIcon(tk.getImage("yellow_bullet.bmp")); private ImageIcon redicon = new ImageIcon(tk.getImage("red_bullet.bmp")); private JPanel coloredpanel = new JPanel(); private JButton yellowbutton = new JButton(yellowIcon); private JButton redbutton = new JButton(redIcon); private JMenuBar menubar = new JMenuBar(); private JMenu colormenu = new JMenu("Color"); private JMenuItem yellowmenuitem = new JMenuItem(yellowIcon); private JMenuItem redmenuitem = new JMenuItem(redIcon); private JPopupMenu popupmenu = new JPopupMenu(); private JMenuItem yellowpopupitem = new JMenuItem(yellowIcon); private JMenuItem redpopupitem = new JMenuItem(redIcon); private static final String YELLOW_COMMAND = "YELLOW_COMMAND"; private static final String RED_COMMAND = "RED_COMMAND";

public ColorCommandFrame1() { super("colorcommandframe1"); setdefaultcloseoperation(jframe.exit_on_close); setextendedstate(jframe.maximized_both); initbuttons(); initpopupmenu(); initmenu(); public void initbuttons() { yellowbutton.setactioncommand(yellow_command); redbutton.setactioncommand(red_command); yellowbutton.addactionlistener(this); redbutton.addactionlistener(this); coloredpanel.add(yellowbutton); coloredpanel.add(redbutton); Container contentpane = getcontentpane(); contentpane.add(coloredpanel);

public void initpopupmenu() { yellowpopupitem.setactioncommand(yellow_command); redpopupitem.setactioncommand(red_command); yellowpopupitem.addactionlistener(this); redpopupitem.addactionlistener(this); popupmenu.add(yellowpopupitem); popupmenu.add(redpopupitem); coloredpanel.addmouselistener(new MouseAdapter() { public void mousepressed(mouseevent e) { maybeshowpopup(e); public void mousereleased(mouseevent e) { maybeshowpopup(e); private void maybeshowpopup(mouseevent e) { if (e.ispopuptrigger()) { popupmenu.show(e.getcomponent(), e.getx(), e.gety()); );

public void initmenu() { yellowmenuitem.setactioncommand(yellow_command); redmenuitem.setactioncommand(red_command); yellowmenuitem.addactionlistener(this); redmenuitem.addactionlistener(this); colormenu.add(yellowmenuitem); colormenu.add(redmenuitem); menubar.add(colormenu); setjmenubar(menubar); public void actionperformed(actionevent ae) { String command = ae.getactioncommand(); if (command.equals(yellow_command)) coloredpanel.setbackground(color.yellow); else if (command.equals(red_command)) coloredpanel.setbackground(color.red);

Example https://www.tutorialspoint.com/design_pattern/command_pattern.htm

Common Design Patterns Creational Structural Behavioral Factory Singleton Builder Prototype Decorator Adapter Facade Flyweight Component Architecture Strategy Template Observer Command Iterator State Textbook: Head First Design Patterns

What s the problem? Iteration you have to perform some operation on a sequence of elements in a given data structure Solution: Iterator Pattern a.k.a. Iteration Abstraction iterate over a group of objects without revealing details of how the items are obtained https://www.youtube.com/watch?v=pganyj1dvvu

Iterator An Iterator produces proper elements for processing Defining an Iterator may be complex Using an Iterator must be simple they re all used in the same way E.g. update() all elements of List list: Iterator it; for (it=list.listiterator(); it.hasnext(); ) it.next().update(); Makes iteration through elements of a set higher level Separates the production of elements for iteration from the operation at each step in the iteration.

Iterator (cont d) Iterator is a design pattern that is encountered very often. Problem: Mechanism to operate on every element of a set. Context: The set is represented in some data structure (list, array, hashtable, etc.) Solution: Provide a way to iterate through every element. Common Classes using Iterators in Java API StringTokenizer Vector, ArrayList, etc Even I/O streams work like Iterators

public interface Iterator { // Returns true if there are more // elements to iterate over; false // otherwise public boolean hasnext(); Iterator (in Java) // If there are more elements to // iterate over, returns the next one. // Modifies the state this to record // that it has returned the element. // If no elements remain, throw // NoSuchElementException. public Object next() throws NoSuchElementException; public void remove();

Iterator vs. Enumeration Java provides another interface Enumeration for iterating over a collection. Iterator is newer (since JDK 1.2) has shorter method names has a remove() method to remove elements from a collection during iteration Iterator Enumeration hasnext() hasmoreelements() next() remove() - nextelement() Iterator is recommended for new implementations.

Example Loop controlled by next() private Payroll payroll = new Payroll();... public void decreasepayroll() { Iterator it = payroll.getiterator(); while (it.hasnext()) { Employee e = (Employee)it.next(); double salary = e.getsalary(); e.setsalary(salary*.9); for (Employee emp : payroll) {

Implementing an Iterator public class Payroll { private Employee[] employees; private int num_employees;... // An iterator to loop through all Employees public Iterator getiterator() { return new EmplGen();... private class EmplGen implements Iterator { // see next slide...

Implementing an Iterator private class EmplGen implements Iterator { private int n = 0; public boolean hasnext() { return n < num_employees; state of iteration captured by index n returns true if there is an element left to iterate over public Object next() throws NoSuchElementException { Object obj; if (n < num_employees) { obj = employees[n]; n++; return obj; else throw new NoSuchElementException ("No More Employees"); returns the next element in the iteration sequence

Example https://www.tutorialspoint.com/design_pattern/iterator_pattern.htm

Common Design Patterns Creational Structural Behavioral Factory Singleton Builder Prototype Decorator Adapter Facade Flyweight Component Architecture Strategy Template Observer Command Iterator State Textbook: Head First Design Patterns

State Pattern Dynamically change the representation of an object. also called Data Abstraction Users of the object are unaware of the change. Example: Implement a set as a Vector if the number of elements is small Implement a set as a Hashtable if the number of elements is large State pattern is used only on mutable objects. https://www.youtube.com/watch?v=8jy_fxi1oza

public class Set { private Object elements; Example: Set public boolean isin(object member){ if (elements instanceof Vector) // search using Vector methods else // search using Hashtable methods public void add(object member){ if (elements instanceof Vector) // add using Vector methods else // add using Hashtable methods

Using the state pattern: SetRep public interface SetRep { public void add(object member); public boolean isin(object member); public int size(); public void remove(); public class SmallSet implements SetRep { private Vector set; public void add(object element) {... public void remove() {...... public class LargeSet implements SetRep { private Hashtable set; public void add(object element) {... public void remove() {......

Using the state pattern: a new Set public class Set { private SetRep rep; private int threshold; public void add(object element) { if (rep.size() == threshold) rep = new LargeSet(rep.elements()); rep.add(element); public void remove(object element) { rep.remove(elem); if (rep.size == threshold) rep = new SmallSet(rep.elements());

Example https://www.tutorialspoint.com/design_pattern/state_pattern.htm

Chain of Responsibility Composite Interpreter Mediator Memento Proxy Visitor There are others too