ECE452/CS446/SE464 Design Patterns: Part I Answers A Tutorial by Peter Kim Based on slides prepared by Krzysztof Pietroszek.

Slides:



Advertisements
Similar presentations
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Advertisements

General OO Concepts Objectives For Today: Discuss the benefits of OO Programming Inheritance and Aggregation Abstract Classes Encapsulation Introduce Visual.
Containers and Components 1.Containers collect GUI components 2.Sometimes, want to add a container to another container 3.Container should be a component.
Chapter 4 (Horstmann’s Book) Interface Types and Polymorphism: Graphics, Timer, Animation Hwajung Lee.
INHERITANCE BASICS Reusability is achieved by INHERITANCE
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Inheritance Writing and using Classes effectively.
Decorator Pattern Applied to I/O stream classes. Design Principle Classes should be open for extension, but closed for modification –Apply the principle.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Inheritance Reserved word protected Reserved word super
Classes and Objects: Recap A typical Java program creates many objects which interact with one another by sending messages. Through the objects interactions,
1 Review of classes and subclasses M fast through this material, since by now all have seen it in CS100 or the Java bootcamp First packages Then classes.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Recommendation: Play the game and attempt to answer the questions yourself without looking at the answers. You’ll learn much less if you just look at the.
Classes and Objects  A typical Java program creates many objects which interact with one another by sending messages. Through the objects interactions,
Design patterns Observer,Strategi, Composite,Template (Chap 5, 6)
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Networking with Java CSc 335 Object-Oriented Programming and Design Spring 2009.
Io package as Java’s basic I/O system continue’d.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
Design Patterns and Graphical User Interfaces Horstmann ,
CISC6795: Spring Object-Oriented Programming: Polymorphism.
CS 4240: Bridge and Abstract Factory Readings:  Chap. 10 and 11 Readings:  Chap. 10 and 11.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
18 April 2005CSci 210 Spring Design Patterns 1 CSci 210.
Decorator Design Pattern Rick Mercer CSC 335: Object-Oriented Programming and Design.
10-Nov-15 Java Object Oriented Programming What is it?
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
Week 6, Class 1 & 2: Decorators Return Exam Questions about lab due tomorrow in class? Threads Locking on null object invokeLater & the squares example.
Programming in Java CSCI-2220 Object Oriented Programming.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Review Class Inheritance, Abstract, Interfaces, Polymorphism, GUI (MVC)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
OBSERVER DESIGN PATTERN. Behavioral Patterns  Behavioral patterns are those patterns that are most specifically concerned with communication between.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
Object Oriented Programming
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Parallel Processing (CS526) Spring 2012(Week 8).  Shared Memory Architecture  Shared Memory Programming & PLs  Java Threads  Preparing the Environment.
Lecture 14 Inheritance vs Composition. Inheritance vs Interface Use inheritance when two objects share a structure or code relation Use inheritance when.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Decorator Design Pattern Rick Mercer CSC 335: Object-Oriented Programming and Design.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Proxy Pattern defined The Proxy Pattern provides a surrogate or placeholder for another object to control access to it by creating a representative object.
Watching the movie the hard way…. Page 256 – Head First Design Patterns.
The Decorator Pattern (Structural) ©SoftMoore ConsultingSlide 1.
CS 210 Proxy Pattern Nov 16 th, RMI – A quick review A simple, easy to understand tutorial is located here:
ECE452/CS446/SE464 Design Patterns: Part I Questions A Tutorial by Peter Kim Based on slides prepared by Krzysztof Pietroszek.
StarBuzz Coffee Recipe Boil some water Brew coffee in boiling water Pour coffee in cup Add sugar and milk Tea Recipe Boil some water Steep tea in boiling.
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
Design Patterns. Outline Purpose Purpose Useful Definitions Useful Definitions Pattern Overview Pattern Overview.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Object-Oriented Programming: Polymorphism Chapter 10.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
CS 350 – Software Design The Decorator Pattern – Chapter 17 In this chapter we expand our e-commerce case study and learn how to use the Decorator Pattern.
Creating Java Applications (Software Development Life Cycle) 1. specify the problem requirements - clarify 2. analyze the problem - Input? Processes? Output.
COMPOSITE PATTERN NOTES. The Composite pattern l Intent Compose objects into tree structures to represent whole-part hierarchies. Composite lets clients.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
The Decorator Pattern Decorators in Java I/O classes SE-2811 Dr. Mark L. Hornick 1.
CS 210 Introduction to Design Patterns September 14 th, 2006.
IB Computer Science Content developed by Dartford Grammar School Computer Science Department UML.
Objectives Describe polymorphism
7. Decorator, Façade Patterns
7. Decorator SE2811 Software Component Design
7. Decorator, Façade Patterns
Software Design Lecture : 35.
Software Design Lecture : 36.
Presentation transcript:

ECE452/CS446/SE464 Design Patterns: Part I Answers A Tutorial by Peter Kim Based on slides prepared by Krzysztof Pietroszek

Problem 1 public class GUI { … public void setPerson(Person person) { nameLabel.setText(person.getName()); ageLabel.setText(person.getAge()); } public class Person { protected String name; … public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() {…} public void setAge(int age) {…} } To display Person on GUI, GUI.setPerson(Person) must be invoked explicitly. What design pattern could be used so that changes to Person are more implicitly and “automatically” reflected in GUI and potentially in other classes that are interested in Person? Show a) the design pattern and b) an interaction diagram demonstrating a change in Person

Answer 1a): Observer (behavioural) design pattern Person +setName(name: String): void +getName(): String +setAge(age: int): void +getAge(): int -name: String -age: int GUI +GUI(person: Person): GUI +update(): void -nameLabel: Label -ageLabel: Label *1 { this.person = person; this.person.attach(this); } { nameLabel = person.getName(); ageLabel = person.getAge().toString(); } { this.age = age; notify(); } { this.name = name; notify(); } What’s the problem between Observer.update() and Subject.getState() here? Granularity of updates (e.g. age updated even though only name was changed)

Answer 1b) p:Person gui:GUI :Program p := new Person() gui := new GUI(p) attach(gui) setAge(23) notify(AGE) update(AGE) getAge() Overlapping execution occurrences on the same lifeline are represented by overlapping rectangles

Problem 2 ● Assume that you are implementing a file system. The main concepts in a file system are directories and files. A directory may contain several files and directories. Additionally, you would like to treat files and directories in a uniform way as nodes, i.e., you would like to be able to write code that can treat both files and directories using the same interface. ➔ What design pattern could you use to achieve these goals? ➔ Draw a class diagram explaining your design.

Answer 2 ● Composite Pattern

Problem 3: Java API related What design pattern is java.util.Collections.sort(List, Comparator) method an example of? Draw a class diagram and draw some sample code. package java.util; public interface Comparator { public int compare (Object arg1, Object arg2); … }

Answer 3: Strategy public class AgeComparator implementsComparator { … public int compare(Object arg1, arg2) { Age a1 = (Age)arg1; Age a2 = (Age)arg2; if(a1.getValue() > a1.getValue()) return 1; else if(a1.getValue() < a2.getValue()) return -1; return 0; } Collections.sort(ages, new AgeComparator()); Inside java.util.Collections.sort(.), comparator.compare(Object, Object) is used *somehow*: void Collections.sort(List list, Comparator comparator) { … int comparison = comparator.compare(list.get(i), list.get(i+1)); … }

Problem 4: Java API related Consider the following Java I/O streams, where an indentation represents class inheritance (e.g. FileOutputStream extends OutputStream). OutputStream: the generic output stream. FileOutputStream: output stream for writing to files. FilterOutputStream: takes a regular OutputStream as an input and performs some filtering operations on it. DeflaterOutputStream: performs compression on the input OutputStream. ZipOutputStream: produces a compressed output of “Zip” format. GZIPOutputStream: produces a compressed output of “GZIP” format. What design pattern is evident (hint: FilterOutputStream)? Draw a class diagram and provide a sample code.

Answer 4: Decorator (Structural) public class FilterOutputStream extends OutputStream { /** * The underlying output stream to be filtered. */ protected OutputStream out; /** * Creates an output stream filter built on top of the specified * underlying output stream. */ public FilterOutputStream(OutputStream out) { this.out = out; } public void write(int b) throws IOException { out.write(b); } … } 1 1 public class DeflaterOutputStream extends FilterOutputStream { public void write(int b) throws IOException { bCompressed = compress(b); super.write(bCompressed); }

Problem 5 a) A commonly cited advantage of the Decorator design pattern is that it avoids subclass explosion. Explain this using an example. b) Commonly cited disadvantages of the Decorator design pattern are that it allows i) identity crisis and ii) interface occlusion. Why are these problems not evident with subclassing? Explain these using an example.

Answer 5a) Component FrameableScrollableResizable N functionalities typically represented in N subclasses But representing combinations of N functionalities as subclasses means, for example, {(N choose 1) + (N choose 2) + … + (N choose N) – invalid number of combinations} subclasses Frameable Scrollable Frameable Resizable Scrollable Resizable FrameableScrollable Resizable Using the Decorator design pattern N combinations are represented through, for example, {(N choose 1) + (N choose 2) + … + (N choose N) – invalid number of combinations} objects. However, there are only N classes. Object explosion not as bad as [sub]class explosion as the former is more manageable and much smaller. Component FrameableScrollableResizable f: Frameables: Scrollabler: Resizable3 choose 1 3 choose 2fs: Frameablefr: Frameablesr: Scrollable fsr: Frameable3 choose 3 Objects are composed from right to left. E.g. fs means that s:Scrollable is composed by f:Frameable ComponentDecoratorWindow 1 1

Answer 5b) Identity crisis Clients are referencing the undecorated object ‘c’ initially. ‘c’ is decorated with ‘cd’, an instance of ComponentDecorator. Clients must update the reference ‘c’ to ‘cd’. Hard to update all the clients (especially with many scattered object references), e.g. Client1 is not updated. With subclassing, there’s only one object so there’s no such problem Interface occlusion Interface of the component is blocked by the decorator in the sense that the decorator has to explicitly delegate methods to the component E.g. If interface of Component class evolves (e.g. dispose() is added), then the implementation of the decorator must also evolve so that the method calls will be delegated to the component (e.g. dispose() calls c.dispose()). Component FrameableScrollableResizable ComponentDecorator 1 1 paint(): void dispose(): void c.paint(); Client1 Client2 c: Component cd: ComponentDecorator Basically, problems arise because there are two objects, whereas with subclassing, there is only one object.