Design Patterns 2 Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

Based on Java Software Development, 5th Ed. By Lewis &Loftus
OOP in Java – Inner Classes Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Object-Oriented Design & Programming Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Class Design Lecture 6, Tue Jan
Software Development Study Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Department of Computer Science University of Maryland, College Park
Chapter 10: Inheritance and Polymorphism
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Object-Oriented Design 2 Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CSE 331 Software Design & Implementation Hal Perkins Winter 2013 Design Patterns Part 3 (Slides by Mike Ernst and David Notkin) 1.
Ranga Rodrigo. Class is central to object oriented programming.
Practical Object-Oriented Design with UML 2e Slide 1/1 ©The McGraw-Hill Companies, 2004 PRACTICAL OBJECT-ORIENTED DESIGN WITH UML 2e Chapter 2: Modelling.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Observer Design Pattern Source: Design Patterns – Elements of Reusable Object- Oriented Software; Gamma, et. al.
Implementing Design Patterns Using Java St. Louis Java Special Interest Group Eric M. Burke Object Computing, Inc. Presented on July 9, 1998 (updated July.
Introduction to Object-Oriented Programming
CSC 313 – Advanced Programming Topics. Observer Pattern Intent  Efficiently perform 1-to-many communication  Easy to respond dynamically when event(s)
Design Patterns Lecture III. What Is A Pattern? Current use comes from the work of the architect Christopher Alexander Alexander studied ways to improve.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
Go4 Visitor Pattern Presented By: Matt Wilson. Introduction 2  This presentation originated out of casual talk between former WMS “C++ Book Club” (defunct.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Chapter 19 Designing the GUI front-end: the Model-View-Controller pattern.
CS200 Algorithms and Data StructuresColorado State University Part 4. Advanced Java Topics Instructor: Sangmi Pallickara
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Design Patterns Model – View – Controller. Copyright © 2001 DeLorme 28 November 2001 History ► A framework pattern for reusable applications. ► Depends.
Comp 249 Programming Methodology Chapter 13 Interfaces & Inner Classes Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
3-1 State Design Pattern C Sc 335 Rick Mercer. State Design Pattern State is one of the Behavioral patterns It is similar to Strategy Allows an object.
Chapter 5 Implementing UML Specification (Part II) Object-Oriented Technology From Diagram to Code with Visual Paradigm for UML Curtis H.K. Tsang, Clarence.
CSC 313 – Advanced Programming Topics. Observer Pattern in Java  Java ♥ Observer Pattern & uses everywhere  Find pattern in JButton & ActionListener.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
DESIGN PATTERNS -BEHAVIORAL PATTERNS WATTANAPON G SUTTAPAK Software Engineering, School of Information Communication Technology, University of PHAYAO 1.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
OBSERVER DESIGN PATTERN. Behavioral Patterns  Behavioral patterns are those patterns that are most specifically concerned with communication between.
(1) Introduction to Java GUIs Philip Johnson Collaborative Software Development Laboratory Information and Computer Sciences University of Hawaii Honolulu.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
1 CSE 331 Model/View Separation and Observer Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia.
Interfaces and Inner Classes
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
Observer Pattern Keeping An Eye on Things Need to introduce observer pattern formally first, include book definition & design principle Keeping An Eye.
Creating Java Applications (Software Development Life Cycle) 1. specify the problem requirements - clarify 2. analyze the problem - Input? Processes? Output.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Lecture 12 Inheritance.
Building software from reusable components.
Design Patterns Model – View – Controller
null, true, and false are also reserved.
Introduction to Behavioral Patterns (1)
Interator and Iterable
7. Decorator SE2811 Software Component Design
CIS 199 Final Review.
Chapter 8 Class Inheritance and Interfaces
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
Final and Abstract Classes
Software Design Lecture : 39.
16. Visitors SE2811 Software Component Design
Software Design Lecture : 40.
Presentation transcript:

Design Patterns 2 Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

More Design Patterns Marker interface Label semantic attributes of a class Observer A way of notifying change to a number of classes State Alter an object's behavior when its state changes Visitor Defines a new operation to a class without changing class

Marker Interface Pattern Definition Label semantic attributes of a class Where to use & benefits Need to indicate attribute(s) of a class Allows identification of attributes of objects without assuming they are instances of any particular class

Marker Interface Pattern Example Classes with desirable property GoodProperty Original Store flag for GoodProperty in each class Using pattern Label class using GoodProperty interface Examples from Java Cloneable Serializable

Marker Interface Example public interface GoodProperty { }// no methods class A implements GoodProperty { … } class B { … } class A goodObj = new A(); class B badObj = new B(); if (goodObj instanceof GoodProperty) …// True if (badObj instanceof GoodProperty) …// False

Observer Pattern Definition Updates all dependents of object automatically once object changes state Where to use & benefits One change affects one or many objects Many object behavior depends on one object state Need broadcast communication Maintain consistency between objects Observers do not need to constantly check for changes

Observer Pattern Example Multiple windows (views) for single document Original Each window checks document Window updates image if document changes Using pattern Each window registers as observer for document Document notifies all of its observers when it changes Doc Window Doc Window

Observer Example public interface Observer { public void update(Observable o, Object a) // called when observed object o changes } public class Observable extends Object { protected void setChanged()// changed protected void clearChanged()// no change boolean hasChanged()// return changed? void addObserver(Observer o)// track observers void notifyObservers()// notify if changed, void notifyObservers(Object a)// then clear change }

Observer Example public class MyWindow implements Observer { public openDoc(Observable doc) { doc.addObservers(this); // add window to list } public void update(Observable doc, Object arg) { redraw(doc); // display updated document } public class MyDoc extends Observable { public void edit() { … // edit document setChanged();// mark change notifyObservers(arg);// invokes update() }

State Pattern Definition Represent change in an object’s behavior using its member classes Where to use & benefits Control states without many if-else statements Represent states using classes Every state has to act in a similar manner Simplify and clarify the program

State Pattern Example States representing finite state machine (FSM) Original Each method chooses action depending on state Behavior may be confusing, state is implicit Using pattern State interface defines list of actions for state Define inner classes implementing State interface Finite state machine instantiates each state and tracks its current state Current state used to choose action

State Example – Original Code public class FickleFruitVendor { boolean wearingHat; boolean isHatOn() { return wearingHat; } String requestFruit() { if (wearingHat) { wearingHat = false; return "Banana"; } else { wearingHat = true; return "Apple"; } Wearing Hat Not Wearing Hat Banana Apple

State Example public interface State { boolean isHatOn(); String requestFruit(); } public class WearingHat implements State; public class NotWearingHat implements State;

State Example public class FickleFruitVendor { State wearingHat = new WearingHat(); State notWearingHat = new NotWearingHat(); // explicitly track current state of Vendor State currentState = wearingHat; // behavior of Vendor depends on current state public boolean isHatOn() { return currentState.isHatOn(); } public String requestFruit() { return currentState.requestFruit(); }

State Example class WearingHat implements State { boolean isHatOn() { return true; } String requestFruit() { currentState = notWearingHat; // change state return "Banana"; } class NotWearingHat implements State { boolean isHatOn() { return false; } String requestFruit() { currentState = wearingHat; // change state return "Apple"; } } // end class Wearing Hat Not Wearing Hat Banana Apple

Visitor Pattern Definition Define operations on elements of data structures without changing their classes Where to use & benefits Add operations to classes with different interfaces Can modify operations on data structure easily Encapsulate operations on elements of data structure Decouples classes for data structure and algorithms Crossing class hierarchies may break encapsulation

Visitor Pattern Example Print elements in collection of objects Original Iterator chooses action based on type of object Many if-else statements Using pattern Visitor interface defines actions during visit Visitable interface allow objects to accept visit Action automatically selected by polymorphic functions through double dispatch

Visitor Example – Original Code public void messyPrintCollection(Collection c) { Iterator iterator = c.iterator() while (iterator.hasNext()) { Object o = iterator.next(); if (o instanceof Collection) messyPrintCollection((Collection)o); else if (o instanceof String) System.out.println("'"+o.toString()+"'"); // add ' else if (o instanceof Float) System.out.println(o.toString()+"f"); // add f else System.out.println(o.toString()); }

Visitor Example public interface Visitor { public void visitCollection(Collection c); public void visitString(String string); public void visitFloat(Float float); } public interface Visitable { public void accept(Visitor v); }

Visitor Example public class VisitableString implements Visitable { private String value; public VisitableString(String s) { value = s; } public void accept(Visitor v) { v.visitString(this); } } public class VisitableFloat implements Visitable { private Float value; public VisitableFloat(Float f) { value = f; } public void accept(Visitor v) { v.visitFloat(this); } } Double dispatch

Visitor Example public class PrintVisitor implements Visitor { public void visitCollection(Collection c) { Iterator iterator = c.iterator() while (iterator.hasNext()) { Object o = iterator.next(); if (o instanceof Visitable) ((Visitable) o).accept(this); } public void visitString(String s) { System.out.println("'"+s+"'"); } public void visitFloat(Float f) { System.out.println(f.toString()+"f"); }

UML Class Diagram of Abstract Visitor

Summary Design patterns can be useful for designing quality software Using design patterns successfully requires familiarity & experience