Introduction to Design Patterns 1CS 221 - Computer Science II.

Slides:



Advertisements
Similar presentations
Lecture 9 Design Patterns CSCI – 3350 Software Engineering II Fall 2014 Bill Pine.
Advertisements

Observer Method 1. References Gamma Erich, Helm Richard, “Design Patterns: Elements of Reusable Object- Oriented Software” 2.
Object-Oriented Design Patterns Composite Singleton State Observer … Autumn 2012UCN Technology: IT/Computer Science1.
Design Patterns for Object Oriented systems CSC 515 Ashwin Dandwate.
Observer Pattern Fall 2005 OOPD John Anthony. What is a Pattern? “Each pattern describes a problem which occurs over and over again in our environment,
05/26/2004www.indyjug.net1 Indy Java User’s Group June Knowledge Services, Inc.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 7 Object Oriented Programming in Java Advanced Topics Collection.
Design and Programming Patterns Associated with Java Networking by Margaret Toews cs843, Spring 2003.
Dept. of Computer Engineering, Amirkabir University of Tech. 1 Design Patterns Dr. Noorhosseini Introduction.
BehavioralCmpE196G1 Behavioral Patterns Chain of Responsibility (requests through a chain of candidates) Command (encapsulates a request) Interpreter (grammar.
Design Patterns CS is not simply about programming
James Tam Introduction To Design Patterns You will learn about design techniques that have been successfully applied to different scenarios.
Spring 2010CS 2251 Design Patterns. Spring 2010CS 2252 What is a Design Pattern? "a general reusable solution to a commonly occurring problem in software.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Design Patterns.
PRESENTED BY SANGEETA MEHTA EECS810 UNIVERSITY OF KANSAS OCTOBER 2008 Design Patterns.
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
Introduction to software design patterns For CSE 3902 By: Matt Boggus.
Design Patterns Discussion of pages: xi-11 Sections: Preface, Forward, Chapter
Design Patterns Trends and Case Study John Hurst June 2005.
Chapter 7 GRASP patterns Dr Seham Mostefai CAP 252.
©2007 · Georges Merx and Ronald J. NormanSlide 1 Chapter 11 Reality Check: Java Programming in the Real World.
Session 05: C# Patterns Algorithm Patterns: Sweep Search FEN AK IT: Softwarekonstruktion.
02 - Behavioral Design Patterns – 2 Moshe Fresko Bar-Ilan University תשס"ח 2008.
Implementing Design Patterns Using Java St. Louis Java Special Interest Group Eric M. Burke Object Computing, Inc. Presented on July 9, 1998 (updated July.
Design patterns. What is a design pattern? Christopher Alexander: «The pattern describes a problem which again and again occurs in the work, as well as.
05 - Patterns Intro.CSC4071 Design Patterns Designing good and reusable OO software is hard. –Mix of specific + general –Impossible to get it right the.
CSE 332: Design Patterns (Part I) Introduction to Design Patterns Design patterns were mentioned several times so far –And the Singleton Pattern was discussed.
An Introduction to Design Patterns. Introduction Promote reuse. Use the experiences of software developers. A shared library/lingo used by developers.
Introduction to Design Patterns 1CS Computer Science II.
Copyright © 2002, Systems and Computer Engineering, Carleton University Patterns.ppt * Object-Oriented Software Development Part 11.
BTS430 Systems Analysis and Design using UML Design Patterns.
January 12, Introduction to Design Patterns Tim Burke References: –Gamma, Erich, et. al. (AKA, The Gang of Four). Design Patterns: Elements of Reusable.
SOFTWARE DESIGN AND ARCHITECTURE LECTURE 27. Review UML dynamic view – State Diagrams.
Introduction to Design Patterns 1CS Computer Science II.
Patterns and Reuse. Patterns Reuse of Analysis and Design.
Behavioral Design Patterns Morteza Yousefi University Of Science & Technology Of Mazandaran 1of 27Behavioral Design Patterns.
L11-12: Design Patterns Definition Iterator (L4: Inheritance)‏ Factory (L4: Inheritance)‏ Strategy (L5: Multiple Inheritance)‏ Composite (L6: Implementation.
Design Patterns Introduction General and reusable solutions to common problems in software design SoftUni Team Software University
Design Principle & Patterns by A.Surasit Samaisut Copyrights : All Rights Reserved.
ECE450S – Software Engineering II
1 A Brief Introduction to Design Patterns Based on materials from Doug Schmidt 1.
05/26/2004www.indyjug.net1 Indy Java User’s Group May Knowledge Services, Inc.
CS 160: Software Engineering October 22 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
CSC 480 Software Engineering Design With Patterns.
Behavioural Design Patterns Quote du jour: ECE450S – Software Engineering II I have not failed. I've just found 10,000 ways that won't work. - Thomas Edison.
Copyright © Active Frameworks Inc. - All Rights Reserved - V2.0Design Pattern Catalog - Page L3-1 PS95&96-MEF-L10-1 Dr. M.E. Fayad Creationa.
OBSERVER DESIGN PATTERN. Behavioral Patterns  Behavioral patterns are those patterns that are most specifically concerned with communication between.
CS212: Object Oriented Analysis and Design Lecture 37: Design Pattern.
Manali Joshi1 The Observer Design Pattern Presented By: Manali Joshi.
Behavioral Patterns1 Nour El Kadri SEG 3202 Software Design and Architecture Notes based on U of T Design Patterns class.
CS251 – Software Engineering Lectures 18: Intro to DP Slides by Rick Mercer, Christian Ratliff, Oscar Nierstrasz and others 1 و ابتغ فيما آتاك الله الدار.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAMMING PRACTICES Model View.
Duke CPS Programming Heuristics l Identify the aspects of your application that vary and separate them from what stays the same ä Take what varies.
1 Good Object-Oriented Design Dr. Radu Marinescu Lecture 4 Introduction to Design Patterns.
The Observer Design Pattern Author :Erich Gamma, et al. Source :Elements of Reusable Object-Oriented Software Speaker : Chiao-Ping Chang Advisor : Ku-Yaw.
Design Patterns CSCE 315 – Programming Studio Spring 2013.
1 Lecture Material Design Patterns Visitor Client-Server Factory Singleton.
Design Patterns: MORE Examples
Design Patterns: Brief Examples
Software Design Patterns
A Brief Introduction to Design Patterns
Design Patterns Introduction
Design Patterns.
Observer Design Pattern
Web Programming Language
Patterns.
Introduction to Design Patterns
Informatics 122 Software Design II
Software Design Lecture : 39.
Presentation transcript:

Introduction to Design Patterns 1CS Computer Science II

2 Overview Design Patterns in Software Why? What are design patterns? What they’re good for How we develop / classify them The Iterator Pattern CS Computer Science II

3 Recurring Design Structures OO systems exhibit recurring structures that promote abstraction flexibility modularity elegance Therein lies valuable design knowledge Problem: Capturing, communicating, and applying this knowledge CS Computer Science II

4 Design Patterns "Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice." Christopher Alexander, A Pattern Language: Towns/Buildings/Construction, 1977 A object-oriented design pattern systematically names, explains and evaluates an important and recurring design in object-oriented systems

Patterns in engineering How do other engineers find and use patterns? Mature engineering disciplines have handbooks describing successful solutions to known problems Automobile designers don't design cars from scratch  Reuse standard designs with successful track records Should software engineers make use of patterns? Why?  Developing software from scratch is expensive  Patterns support reuse of software architecture and design

CS Computer Science II6 Design Patterns The landmark book on software design patterns is: Design Patterns: Elements of Reusable Object-Oriented Software Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides Addison-Wesley, 1995 This is also known as the GOF (“Gang- of-Four”) book.

7 A Design Pattern… abstracts a recurring design structure comprises class and/or object  dependencies  structures  interactions  conventions names / specifies the design structure explicitly distills design experience CS Computer Science II

8 Goals Codify good design distill / generalize experience aid to novices / experts alike Give design structures explicit names common vocabulary reduced complexity greater expressiveness Capture and preserve design information articulate design decisions succinctly improve documentation Facilitate restructuring / refactoring patterns are interrelated additional flexibility CS Computer Science II

9 Design Pattern Template (1st half) N AME scope purpose Intent short description of the pattern & its purpose Also Known As Any aliases this pattern is known by Motivation motivating scenario demonstrating pattern’s use Applicability circumstances in which pattern applies Structure graphical representation of the pattern using modified UML notation Participants participating classes and/or objects & their responsibilities CS Computer Science II

10 Design Pattern Template (2nd half)... Collaborations how participants cooperate to carry out their responsibilities Consequences the results of application, benefits, liabilities Implementation pitfalls, hints, techniques, plus language-dependent issues Sample Code sample implementations in C++, Java, C#, Smalltalk, C, etc. Known Uses examples drawn from existing systems Related Patterns discussion of other patterns that relate to this one CS Computer Science II

11 O BSERVER object behavioral Intent define a one-to-many dependency between objects so that when one object changes state, all dependents are notified & updated Applicability an abstraction has two aspects, one dependent on the other a change to one object requires changing untold others an object should notify unknown other objects Structure

12 O BSERVER (cont’d) object behavioral Consequences +modularity: subject & observers may vary independently +extensibility: can define & add any number of observers +customizability: different observers offer different views of subject –unexpected updates: observers don’t know about each other –update overhead: might need hints or filtering Implementation subject-observer mapping dangling references update protocols: the push & pull models registering modifications of interest explicitly Known Uses Smalltalk Model-View-Controller (MVC) InterViews (Subjects & Views, Observer/Observable) Andrew (Data Objects & Views) Pub/sub middleware (e.g., CORBA Notification Service, Java Messaging Service) Mailing lists

Iterator Design Pattern CS Computer Science II13

14 I TERATOR object behavioral Intent access elements of a container without exposing its representation Applicability require multiple traversal algorithms over a container require a uniform traversal interface over different containers when container classes & traversal algorithm must vary independently Structure CS Computer Science II

15 I TERATOR (cont’d) object behavioral int main (int argc, char *argv[]) { vector args; for (int i = 0; i < argc; i++) args.push_back (string (argv[i])); for (vector ::iterator i (args.begin ()); i != args.end (); i++) cout << *i; cout << endl; return 0; } Iterators are used heavily in the C++ Standard Template Library (STL) The same iterator pattern can be applied to any STL container! for (Glyph::iterator i = glyphs.begin (); i != glyphs.end (); i++)... CS Computer Science II

16 I TERATOR (cont’d) object behavioral Consequences +flexibility: aggregate & traversal are independent +multiple iterators & multiple traversal algorithms –additional communication overhead between iterator and aggregate Implementation internal versus external iterators violating the object structure’s encapsulation robust iterators synchronization overhead in multi-threaded programs batching in distributed & concurrent programs Known Uses C++ STL iterators JDK Enumeration, Iterator Unidraw Iterator CS Computer Science II

Design Patterns are NOT Data structures that can be encoded in classes and reused as is (i.e., linked lists, hash tables) Complex domain-specific designs (for an entire application or subsystem) If they are not familiar data structures or complex domain-specific subsystems, what are they? They are: “Descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context.”

Benefits of Design Patterns Design patterns enable large-scale reuse of software architectures and also help document systems Patterns explicitly capture expert knowledge and design tradeoffs and make it more widely available Patterns help improve developer communication Pattern names form a common vocabulary

19 Liabilities of Patterns Require significant tedious and error-prone human effort to handcraft pattern implementations design reuse Can be deceptively simple uniform design vocabulary May limit design options Leaves some important details unresolved CS Computer Science II

20

CS Computer Science II21 Iterating Through A Vector Suppose we want to “step through” a Vector object, retrieving each of the objects stored in the vector one at a time:

CS Computer Science II22 Iterating Through A Vector import java.util.*; public class IterationExample { public static void main(String args[]) { Vector v = new Vector(); // Put some Complex number // objects in the vector. v.addElement(new Complex(3.2, 1.7)); v.addElement(new Complex(7.6)); v.addElement(new Complex()); v.addElement(new Complex(-4.9, 8.3)); Complex c; for (int i = 0; i < v.size(); i++) { c = (Complex)v.elementAt(i); System.out.println(c); }

CS Computer Science II23 Iterating Through A Vector This approach works well for vectors because the elements of a vector can be retrieved by specifying their position: v.elementAt(i); We start by retrieving element 0, then retrieve element 1, etc., until we retrieve the last element (at position v.size()- 1)

CS Computer Science II24 What About Other Collection Classes? This approach doesn't work well for all collection classes: what would a position (i.e. index) mean for a Set ? values stored in a Hashtable object are retrieved by keys, not by position Is it possible to come up with a more general approach, that can be used to iterate over any collection of objects? There must be a general design solution to this…

CS Computer Science II25 Collection Classes & Iterators The Collection interface provides an iterator() method to be implemented by all concrete collections: Iterator iterator() Collection plays the role of the “Aggregate” in the GoF Iterator pattern A “ConcreteAggregate” (i.e. Vector, LinkedList …) implementing this method should create and return a iterator object

CS Computer Science II26 Iterator Objects An Iterator object provides two main methods: public boolean hasNext()  returns true if the Iterator object has more elements (objects) that have not yet been returned by next() public Object next()  returns the next element (object) from the iteration

CS Computer Science II27 Iterating Through a Vector // Create a vector object and initialize // it with Complex objects Complex c; Iterator i; i = v.iterator(); while (i.hasNext()) { c = (Complex)i.next(); System.out.println(c); }

CS Computer Science II28 Iterating Any Collection For instance, the code below shows how AbstractCollection implements addAll() without making any assumption on the nature of the collection that is passed as an argument: public boolean addAll(Collection from) { Iterator iter = from.iterator(); boolean modified = false; while (iter.hasNext()) if (add(iter.next())) modified = true; return modified; }

CS Computer Science II29 Building an Iterator Suppose we have a class called CircularList that provides these methods (other CircularList methods not shown here): // Constructor. public CircularList(); // Return the count of the number of // elements in the list. public int count(); // Return the element stored at the specified // position in the CircularList. public Object get(int index); // Remove the element stored at the specified // position in the CircularList. public Object remove(int index);

CS Computer Science II30 Building an Iterator How do we build an iterator (i.e., an Iterator object) for this class? We want an object that lets us do this: CircularList l = new CircularList();... //store integers in the list... Iterator i = l.iterator(); while (i.hasNext()) { System.out.println(i.next()); }

CS Computer Science II31 The Iterator Interface When we look through the documentation for the Java API, we discover that Iterator is an interface, not a class: public interface Iterator { public boolean hasNext(); public Object next(); public void remove(); } An Iterator object is an instance of a class that implements the Iterator interface; i.e., defines the hasNext(), next(), and remove() methods