Object-Oriented Design Patterns CSC 335: Object-Oriented Programming and Design.

Slides:



Advertisements
Similar presentations
Welcome to. Who am I? A better way to code Design Patterns ???  What are design patterns?  How many are there?  How do I use them?  When do I use.
Advertisements

18-1 Verifying Object Behavior and Collaboration Role playing – the act of simulating object behavior and collaboration by acting out an object’s behaviors.
OOP Design Patterns Chapters Design Patterns The main idea behind design patterns is to extract the high level interactions between objects and.
DESIGN PATTERNS OZGUR RAHMI DONMEZ.
05/26/2004www.indyjug.net1 Indy Java User’s Group June Knowledge Services, Inc.
(c) 2009 University of California, Irvine – André van der Hoek1June 13, 2015 – 21:42:16 Informatics 122 Software Design II Lecture 8 André van der Hoek.
Design Patterns CS is not simply about programming
Design Patterns. What are design patterns? A general reusable solution to a commonly occurring problem. A description or template for how to solve a problem.
Visual Basic: An Object Oriented Approach 11 – Patterns in object oriented programming.
Spring 2010CS 2251 Design Patterns. Spring 2010CS 2252 What is a Design Pattern? "a general reusable solution to a commonly occurring problem in software.
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
PRESENTED BY SANGEETA MEHTA EECS810 UNIVERSITY OF KANSAS OCTOBER 2008 Design Patterns.
Object-Oriented Design Patterns CSC 335: Object-Oriented Programming and Design.
Design Patterns Alan Shalloway, James Trott, Design Patterns Explained, Addison-Wesley, Gamma, Helm, Johnson, Vlissides, Design Patterns, Elements.
Model View Controller (MVC) Rick Mercer with a wide variety of others 1.
Object-Oriented Design Patterns CSC 335: Object-Oriented Programming and Design.
Implementing Design Patterns Using Java St. Louis Java Special Interest Group Eric M. Burke Object Computing, Inc. Presented on July 9, 1998 (updated July.
CSE 332: Design Patterns (Part I) Introduction to Design Patterns Design patterns were mentioned several times so far –And the Singleton Pattern was discussed.
CS 350 – Software Design An Introduction to Design Patterns – Chapter 5 A proposition behind design patterns is that quality of software systems can be.
Chapter Five An Introduction to Design Patterns Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information.
CSSE 374: Introduction to Gang of Four Design Patterns
An Introduction to Design Patterns. Introduction Promote reuse. Use the experiences of software developers. A shared library/lingo used by developers.
SOEN 6011 Software Engineering Processes Section SS Fall 2007 Dr Greg Butler
Copyright © 2002, Systems and Computer Engineering, Carleton University Patterns.ppt * Object-Oriented Software Development Part 11.
January 12, Introduction to Design Patterns Tim Burke References: –Gamma, Erich, et. al. (AKA, The Gang of Four). Design Patterns: Elements of Reusable.
Patterns in programming 1. What are patterns? “A design pattern is a general, reusable solution to a commonly occurring problem in software. A design.
SOFTWARE DESIGN AND ARCHITECTURE LECTURE 27. Review UML dynamic view – State Diagrams.
Behavioral Design Patterns Morteza Yousefi University Of Science & Technology Of Mazandaran 1of 27Behavioral Design Patterns.
Design Patterns CSCI 5801: Software Engineering. Design Patterns.
L11-12: Design Patterns Definition Iterator (L4: Inheritance)‏ Factory (L4: Inheritance)‏ Strategy (L5: Multiple Inheritance)‏ Composite (L6: Implementation.
Software Design Patterns (1) Introduction. patterns do … & do not … Patterns do... provide common vocabulary provide “shorthand” for effectively communicating.
CSE 403 Lecture 14 Design Patterns. Today’s educational objective Understand the basics of design patterns Be able to distinguish them from design approaches.
How Would You Solve This? l Suppose that you want to have one and only one instance of a class – Can you think of ever only wanting one instance of a class?
Testing Extensible Design Patterns in OO Frameworks through Scenario Templates D.S. Sanders Software Verification & Validation.
ECE450S – Software Engineering II
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
Mediator Kensho Tsuchihashi. Mediator Page 2 Table of Contents 1.What is Mediator? 2.What problem does Mediator solve? 3.Advantage and Disadvantage 4.Additional.
1 Design Patterns Object-Oriented Design. 2 Design Patterns 4Reuse of design knowledge and experience 4Common in many engineering disciplines 4Avoids.
05/26/2004www.indyjug.net1 Indy Java User’s Group May Knowledge Services, Inc.
Model View Controller (MVC) Bigger than a Pattern: It’s an Architecture Rick Mercer with help from many of others 1.
DESIGN PATTERNS COMMONLY USED PATTERNS What is a design pattern ? Defining certain rules to tackle a particular kind of problem in software development.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Design Patterns. 1 Paradigm4 Concepts 9 Principles23 Patterns.
Design Patterns Introduction
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.
Object-Oriented Design Patterns CSC 335: Object-Oriented Programming and Design.
Model View Controller (MVC) an architecture Rick Mercer with help from many of others 1.
Five Minute Design Patterns Doug Marttila Forest and the Trees May 30, 2009 Template Factory Singleton Iterator Adapter Façade Observer Command Strategy.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
Design Patterns CSCE 315 – Programming Studio Spring 2013.
How Would You Solve This?
The Object-Oriented Thought Process Chapter 15
Chapter 10 Design Patterns.
MPCS – Advanced java Programming
Design Patterns Lecture part 2.
Introduction to Design Patterns
Design Patterns Introduction
SOEN 343 Software Design Computer Science and Software Engineering Department Concordia University Fall 2005 Instructor: Patrice Chalin.
Advanced Programming Behnam Hatami Fall 2017.
Software Engineering Lecture 7 - Design Patterns
08/15/09 Design Patterns James Brucker.
Informatics 122 Software Design II
DESIGN PATTERNS : Introduction
Advanced ProgramMING Practices
Advanced ProgramMING Practices
Informatics 122 Software Design II
Presentation transcript:

Object-Oriented Design Patterns CSC 335: Object-Oriented Programming and Design

Outline Overview of Patterns Iterator Strategy

The Beginning Christopher Alexander, architect –A Pattern Language--Towns, Buildings, Construction –Timeless Way of Building (1979) –“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.” Other patterns: novels (tragic, romantic, crime), movies genres,

“Gang of Four” (GoF) Book Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley Publishing Company, Written by this "gang of four" –Dr. Erich Gamma, then Software Engineer, Taligent, Inc.; –Dr. Richard Helm, then Senior Technology Consultant, DMR Group; –Dr. Ralph Johnson, then and now at University of Illinois, Computer Science Department –Dr. John Vlissides, then a researcher at IBM Thomas J. Watson Research Center. See WikiWiki tribute page

Patterns This book defined 23 patterns in three categories. – Creational patterns deal with the process of object creation – Structural patterns, deal primarily with the static composition and structure of classes and objects – Behavioral patterns, which deal primarily with dynamic interaction among classes and objects Many other patterns have been introduced by others. –For example, the book Data Access Patterns by Clifton Nock introduces 4 decoupling patterns, 5 resource patterns, 5 I/O patterns, 7 cache patterns, and 4 concurrency patterns. –Other pattern languages include telecommunications patterns, pedagogical patterns, analysis patterns –Patterns are mined at places like Patterns ConferencesPatterns Conferences

GoF Patterns – Creational Patterns Abstract Factory Builder Factory Method Prototype Singleton – Structural Patterns Adapter Bridge Composite Decorator Façade Flyweight Proxy – Behavioral Patterns Chain of Responsibility Command Interpreter Iterator Mediator Memento Observer State Strategy Template Method Visitor

Why Study Patterns? Can reuse solutions. –Gives us a head start –Avoids the gotchas later (unanticipated things) –No need to reinvent the wheel Establish common terminology –Design patterns provide a common point of reference –Easier to say, “We need Strategy here.” Provide a higher level prospective –Frees us from dealing with the details too early

Carpenter's Conversation Adapted from Ralph Johnson How should we build the cabinet drawers? Cut straight down into the wood, cut back up 45 degrees a specific length, then go straight back down a specific length, the cut back up at 45 degrees.....

A Higher Level Discussion A high level discussion could have been: –"Should we use a miter joint or a dovetail joint?" –This is a higher, more abstract level –Avoids getting bogged down in details Which level of detail is more efficient?

Consequences of which joint Dovetail joints –are more complex, more expensive to make –withstands climate conditions – dovetail joint remains solid as wood contracts and expands –independent of fastening system –more pleasing to look at Thoughts underneath this question are –Should we make a beautiful durable joint or a cheap and dirty one that lasts until the check clears?

Consequences Carpenters, patterns writers, and software developers discuss consequences –consequences simply refer to cause and effect If we do this, what will happen – both good and bad –also known as the forces that patterns consider Example: If we use Mediator to add and drop courses –Add an extra class that needs reference to several objects –All of the logic and process is confined to one class so any change to the "rules" would be handled there –Reduces dependencies between others objects (simpler design when student does NOT tell the scheduled course to change)

Other advantages Most design patterns make software more modifiable, less brittle –we are using time tested solutions Using design patterns makes software systems easier to change Helps increase the understanding of basic object- oriented design principles –encapsulation, inheritance, interfaces, polymorphism

Style for Describing Patterns We will use this structure in these slides. – Pattern name – Recurring problem: what problem the pattern addresses – Solution: the general approach of the pattern – UML for the pattern Participants: a description of the classes in the UML – Use Example(s): examples of this pattern, in Java

A few Patterns The next slides present two patterns – Iterator Design Pattern You have seen this and probably used it – Strategy Design Pattern that you have used with Layout managers

Pattern: Iterator Name: Iterator (a.k.a Enumeration) Problem: How can you loop over all objects in any collection. You don’t want to change client code when the collection changes. You also want the same interface (methods) Solutions: 1) Have each class implement an interface. 2) Have an interface that works with all collections Consequences: Can change collection class details without changing code to traverse the collection

GoF Version of Iterator page 257 ListIterator First() Next() IsDone() CurrentItem() // Imaginary code ListIterator itr = list.iterator(); for(itr.First(); !itr.IsDone(); itr.Next()) { cout << itr.CurrentItem().toString();

Java version of Iterator interface Iterator boolean hasNext() Returns true if the iteration has more elements. Object next() Returns the next element in the iteration void remove() Removes the most recently visited element

The Iterator interface in use // The Client code // The Client code List bank = new ArrayList (); List bank = new ArrayList (); bank.add(new BankAccount("One", 0.01) ); bank.add(new BankAccount("One", 0.01) ); //... //... bank.add(new BankAccount("Nine thousand", )); bank.add(new BankAccount("Nine thousand", )); String ID = "Two"; String ID = "Two"; Iterator i = bank.iterator(); Iterator i = bank.iterator(); while(i.hasNext()) { while(i.hasNext()) { if(i.next().getID().equals(searchAcct.getID())) if(i.next().getID().equals(searchAcct.getID())) System.out.println("Found " + ref.getID()); System.out.println("Found " + ref.getID()); }

UML Diagram of Java's Iterator and Collections > Iterator hasNext() next() > List iterator() … Context Vector iterator() Iterator hasNext() next() LinkedList iterator() ArrayList iterator()

import java.util.*; public class IterateOverList { public static void main(String[] args) { public static void main(String[] args) { // Change ArrayList to LinkedList // Change ArrayList to LinkedList List names = new ArrayList (); List names = new ArrayList (); names.add("Chris"); names.add("Chris"); names.add("Casey"); names.add("Casey"); names.add("Kim"); names.add("Kim"); Iterator itr = names.iterator(); Iterator itr = names.iterator(); while (itr.hasNext()) while (itr.hasNext()) System.out.println(itr.next()); System.out.println(itr.next()); }}

Composite Design Pattern Strategy

Pattern: Strategy Name : Strategy (a.k.a Policy) Problem : You want to encapsulate a family of algorithms and make them interchangeable. Strategy lets the the algorithm vary independently from the clients that use it (GoF) Solution : Create an abstract strategy class (or interface) and extend (or implement) it in numerous ways. Each subclass defines the same method names in different ways

Design Pattern: Strategy Consequences: –Allows families of algorithms. Known uses: –Layout managers in Java –Different Poker Strategies in 335 Project –Different PacMan chase strategies in 335 Project –TextField validators in dBase and Borland OWL: Will use different algorithms to verify if the user input is a valid integer, double, string, date, yes/no. Eliminates conditional statements

Java Example of Strategy this.setLayout(new FlowLayout()); this.setLayout(new FlowLayout()); this.setLayout(new GridLayout()); this.setLayout(new GridLayout()); In Java, a container HAS-A layout manager –There is a default –You can change a container's layout manager with a setLayout message

Change the stategy at runtime  Demonstrate LayoutControllerFrame.javaLayoutControllerFrame.java private class FlowListener implements ActionListener { // There is another ActionListener for GridLayout public void actionPerformed(ActionEvent evt) { // Change the layout strategy of the JPanel // and tell it to lay itself out centerPanel.setLayout(new FlowLayout()); centerPanel.validate(); }

interface LayoutManager –Java has interface java.awt.LayoutManagerjava.awt.LayoutManager –Known Implementing Classes GridLayout, FlowLayout, ScrollPaneLayout –Each class implements the following methods addLayoutComponent(String name, Component comp) addLayoutComponent(String name, Component comp) layoutContainer(Container parent) layoutContainer(Container parent) minimumLayoutSize(Container parent) minimumLayoutSize(Container parent) preferredLayoutSize(Container parent) preferredLayoutSize(Container parent) removeLayoutComponent(Component comp) removeLayoutComponent(Component comp)

UML Diagram of Strategy General Form Context strategy: Strategy ContextInterface … > Strategy AlgorithmInterface ConcreteClassA AlgorithmInterface ConcreteClassB AlgorithmInterface ConcreteClassC AlgorithmInterface implements

Specific UML Diagram of LayoutManager in Java JPanel layoutMan: LayoutManager size: Dimension setLayout(lm: LayoutManager) setPreferredSize(di:Dimension) > LayoutManager addLayoutComponent() layoutContainer() minimumLayoutSize() GridLayout addLayoutComponent() layoutContainer() minimumLayoutSize() FlowLayout addLayoutComponent() layoutContainer() minimumLayoutSize() ScrollPaneLayout addLayoutComponent() layoutContainer() minimumLayoutSize() implements

Model View Controller Rick Mercer

Outline Model View Controller –Observer as part of MVC –An example of the Observer Design Pattern

Model View Controller (MVC) The intent of MVC is to keep neatly separate objects into one of tree categories –Model The data, the business logic, rules, strategies, and so on –View Displays the model and usually has components that allows user to edit change the model –Controller Allows data to flow between the view and the model The controller mediates between the view and model

Model The Model's responsibilities –Provide access to the state of the system –Provide access to the system's functionality –Can notify the view(s) that its state has changed

View The view's responsibilities –Display the state of the model to the user At some point, the model (a.k.a. the observable) must registers the views (a.k.a. observers) so the model can notify the observers that its state has changed

Controller The controller's responsibilities –Accept user input Button clicks, key presses, mouse movements, slider bar changes –Send messages to the model, which may in turn notify it observers –Send appropriate messages to the view In Java, listeners are controllers

MVC Misunderstood MVC is understood by different people in different ways It is often misunderstood, but most software developers will say it is important; powerful Lets start it right: MVC is a few patterns put together Consider the Observer Pattern

Compound Patterns The observer pattern is part of MVC In Java, you can use Observer support –The model extends Observable –view implements Observer (one method update) –You need to addObservers to the model –The model sends these two messages whenever it thinks the view should be updated setChanged(); notifyObservers();

Model /** * A simple model that changes its color randomly when asked */ import java.awt.Color; import java.util.Observable; import java.util.Random; public class Model extends Observable { private Color currentColor; private static Random generator; // Or set up any color public Model() { generator = new Random(); currentColor = Color.PINK; } public void changeColor() { // Make the colors change seemingly randomly int red = (currentColor.getRed() + generator.nextInt(256)) % 256; int green = (currentColor.getGreen() + generator.nextInt(256)) % 256; int blue = (currentColor.getRed() + generator.nextInt(256)) % 256; currentColor = new Color(red, green, blue); // 1. These two messages are needed to send the // update message to any and all observers setChanged(); notifyObservers(); } public Color getCurrentColor() { return currentColor; }

One Observer /** * This observer prints the current color of the model to the * console An Observer will be sending update messages to this * JPanel after this JPanel has been added as an Observer */ import java.awt.Color; import java.util.Observable; import java.util.Observer; public class ObserverThatPrints implements Observer { public void update(Observable observable, Object arg) { Color color = ((Model) observable).getCurrentColor(); System.out.println("update called, color = " + color); }

Another Observer Write another Observer as a JPanel that shows the color.toString() in a JLabel - name it ObserverPanelWithLabel Get a Controller from the Code Demos Page