CS 350 – Software Design Template Method Pattern Let’s look at two objects public class Coffee { public void prepareRecipe() { public void prepareRecipe()

Slides:



Advertisements
Similar presentations
Continuation of chapter 6…. Nested while loop A while loop used within another while loop is called nested while loop. Q. An illustration to generate.
Advertisements

 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Inheritance // A simple class hierarchy. // A class for two-dimensional objects. class TwoDShape { double width; double height; void showDim() { System.out.println("Width.
Software Engineering Implementation Lecture 3 ASPI8-4 Anders P. Ravn, Feb 2004.
Interfaces CSC 171 FALL 2004 LECTURE 14. Project 1 review public class Rational { private int numerator, denominator; public Rational(int numerator, int.
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Object Oriented Programming in Java. Object Oriented Programming Concepts in Java Object oriented Programming is a paradigm or organizing principle for.
Decorator Pattern Applied to I/O stream classes. Design Principle Classes should be open for extension, but closed for modification –Apply the principle.
The Queue ADT Definition A queue is a restricted list, where all additions occur at one end, the rear, and all removals occur at the other end, the front.
Midterm Exam Discussion. Lab1 Part package cs homework1; abstract class Shape { public abstract double getArea(); public boolean equals(Object.
1 Lecture 23 Searching Overview  What is Searching?  Linear Search and its Implementation.  Brief Analysis of Linear Search.  Binary Search and its.
Using Processing Stream. Predefined Streams System.in InputStream used to read bytes from the keyboard System.out PrintStream used to write bytes to the.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
March 2004Object Oriented Design1 Object-Oriented Design.
Java Threads A tool for concurrency. OS schedules processes Ready Running 200 Blocked A process loses the CPU and another.
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.
SELECTION CSC 171 FALL 2004 LECTURE 8. Sequences start end.
1 Search & Sorting Using Java API Searching and Sorting Using Standard Classes  Searching data other than primitive type.  Comparable interface.  Implementing.
Java Review 3 Rem Collier. Java Wrapper Classes In Java, the term wrapper class commonly refers to a set of Java classes that “objectify” the primitive.
Building Java Programs Binary Search Trees reading: 17.3 – 17.4.
Informatics 122 Software Design II Lecture 6 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.
Io package as Java’s basic I/O system continue’d.
Searching Also: Logarithms. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an.
+ Informatics 122 Software Design II Lecture 9 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
SOFTWARE TECHNOLOGY - I CONSTANTS VARIABLES DATA TYPES.
1 GoF Template Method (pp ) GoF Strategy (pp ) PH Single User Protection (pp ) Presentation by Julie Betlach 6/08/2009.
Exception Handling. Outline What is an Exception How to use exceptions catch ing throw ing Extending the Exception class Declaring using the throws clause.
CS 2511 Fall  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.
1 KC Web & Java – 29 november 2005 – Design Patterns – The Template Method AJAX! KC Web & Java 29 november 2005.
Sorting Algorithms. Sorting Sorting is a process that organizes a collection of data into either ascending or descending order. public interface ISort.
Lecture 8: Object-Oriented Design. 8-2 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Objectives “Good object-oriented programming is really.
‘How to make perfect English tea’ Ewa Pacykowska.
Java Arrays …………. Java Arrays …………. * arrays are objects in Java * arrays are objects in Java * an array variable is a reference * an array variable is.
Behavioral Design Patterns Morteza Yousefi University Of Science & Technology Of Mazandaran 1of 27Behavioral Design Patterns.
Mohammed Al-Dhelaan CSci 253 Object Oriented Design Instructor: Brad Taylor 06/02/2009 Factory Method Pattern.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
Newport Robotics Group 1 Tuesdays, 6:30 – 8:30 PM Newport High School Week 4 10/23/2014.
Review TEST 2 Chapters 4,5,7. QUESTION For which type of operands does the == operator always work correctly: (a) int, (b) double, or (c) String?
CS 210 Final Review November 28, CS 210 Adapter Pattern.
State Design Pattern. Behavioral Pattern Allows object to alter its behavior when internal state changes Uses Polymorphism to define different behaviors.
Cs205: engineering software university of virginia fall 2006 Subtyping and Inheritance David Evans Quiz Friday: classes through.
The Template Method Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Inheritance Type/Subtype Relationship. Inheritance Idea: An object B of one type, termed child class, inherits from another object A of another type,
A: A: double “4” A: “34” 4.
Java Server Sockets ServerSocket : Object to listen for client connection requests Throws IOException accept() method to take the client connection. Returns.
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.
Java Programming Persistent Data Types. Persistent Data Structure A persistent data structure is a data structure having an internal state that never.
Object-Oriented Programming (Java) Review Unit 1 Class Design Basic Console I/O StringTokenizer Exception UML class diagram.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
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.
Last Revision. Question1 Novice Java programmers often write code similar to, class C { public int x;... }... C[] a = new C[10]; for(int i = 0; i < a.length;
Exercise 1 Review OOP tirgul No Outline Polymorphism Exceptions A design example Summary.
Data-Driven Programs Eric Roberts CS 106A February 26, 2016.
CS 210 Introduction to Design Patterns September 14 th, 2006.
Linked Data Structures
Template Method Pattern Iterator Pattern
Introduction to OO Program Design
CS 302 Week 11 Jim Williams, PhD.
2/26/12 Quiz Bowl.
CS Week 13 Jim Williams, PhD.
CS 302 Week 10 Jim Williams.
Review Operation Bingo
Introduction to Behavioral Patterns (3)
null, true, and false are also reserved.
JavaScript Reserved Words
Objects with ArrayLists as Attributes
State Design Pattern.
Exceptions and Exception Handling
Presentation transcript:

CS 350 – Software Design Template Method Pattern Let’s look at two objects public class Coffee { public void prepareRecipe() { public void prepareRecipe() { boilWater(); boilWater(); brewCoffeeGrinds(); brewCoffeeGrinds(); pourInCup(); pourInCup(); addSugarAndMilk(); addSugarAndMilk();} public void boilWater() { System.out.println(“Boiling water”); System.out.println(“Boiling water”);} public void brewCoffeeGrinds { System.out.println(“Dripping Coffee through filter”); System.out.println(“Dripping Coffee through filter”);} public void pourInCup() { System.out.println(“Pouring in cup”); System.out.println(“Pouring in cup”);} public void addSugarAndMilk() { System.out.println(“adding Sugar and Milk”); System.out.println(“adding Sugar and Milk”);}}

CS 350 – Software Design Template Method Pattern Let’s look at two objects public class Tea{ public void prepareRecipe() { public void prepareRecipe() { boilWater(); boilWater(); steepTeaBag(); steepTeaBag(); pourInCup(); pourInCup(); addLemon(); addLemon();} public void boilWater() { System.out.println(“Boiling water”); System.out.println(“Boiling water”);} public void steepTea { System.out.println(“Steeping the tea”); System.out.println(“Steeping the tea”);} public void pourInCup() { System.out.println(“Pouring in cup”); System.out.println(“Pouring in cup”);} public void addLemon() { System.out.println(“adding Lemon”); System.out.println(“adding Lemon”);}

CS 350 – Software Design Template Method Pattern Clearly there is code duplication. Do you think this is a contrived example? Wouldn’t you really say: public void boilWater() { System.out.println(“Boiling water for coffee”); System.out.println(“Boiling water for coffee”);} public void boilWater() { System.out.println(“Boiling water for tea”); System.out.println(“Boiling water for tea”);} As well as: public void pourInCup() { System.out.println(“Pouring coffee in cup”); System.out.println(“Pouring coffee in cup”); public void pourInCup() { System.out.println(“Pouring tea in cup”); System.out.println(“Pouring tea in cup”);

CS 350 – Software Design Template Method Pattern Let’s abstract Coffee and Tea:

CS 350 – Software Design Template Method Pattern Think of it this way: Both recipes follow the same algorithm. 1. Boil some water. 2. Use the hot water to extract the coffee or tea. 3. Pour the resulting beverage into a cup. 4. Add the appropriate condiments to the beverage.

CS 350 – Software Design Template Method Pattern Compare the two prepareRecipe() methods. These can be rewritten as: void prepareRecipe() { boilWater(); boilWater(); brew(); brew(); pourInCup(); pourInCup(); addCondiments(); addCondiments();} Is this better? void prepareRecipe() { boilWater(); brewCoffeeGrinds(); pourInCup(); addSugarAndMilk(); } void prepareRecipe() { boilWater(); SteepTeaBag(); pourInCup(); addLemon(); }

CS 350 – Software Design Template Method Pattern If we implement the new prepare recipe, we now have: public abstract class CaffeineBeverage { final void prepareRecipe() { boilWater(); boilWater(); brew(); brew(); pourInCup(); pourInCup(); addCondiments(); addCondiments();} abstract void brew(); abstract void addCondiments(); void boilWater() { System.out.println(“Boiling water”); System.out.println(“Boiling water”);} void pourInCup() { System.our.println(“Pouring in cup”); System.our.println(“Pouring in cup”);}

CS 350 – Software Design Template Method Pattern public class Tea extends CaffeineBeverage { public void brew() { public void brew() { System.out.println(“Steeping the tea”); System.out.println(“Steeping the tea”);} public void addCondiments() { public void addCondiments() { System.out.println(“Adding Lemon”); System.out.println(“Adding Lemon”);} public class Coffee extends CaffeineBeverage { public void brew() { public void brew() { System.out.println(“Dripping Coffee through filter”); System.out.println(“Dripping Coffee through filter”);} public void addCondiments() { public void addCondiments() { System.out.println(“Adding Sugar and Milk”); System.out.println(“Adding Sugar and Milk”);}

CS 350 – Software Design Template Method Pattern The Template method defines the steps of an algorithm and allows subclasses to provide the implementation for one or more steps.

CS 350 – Software Design Template Method Pattern Template Method Up Close abstract class AbstractClass { final void templateMethod() { final void templateMethod() { primitiveOperation1(); primitiveOperation1(); primitiveOperation2(); primitiveOperation2(); concreteOpertation(); concreteOpertation();} abstract void primitiveOperation1(); abstract void primitiveOperation1(); abstract void primitiveOperation2(); abstract void primitiveOperation2(); void concreteOperation(); { void concreteOperation(); { //implementaiton here //implementaiton here }}

CS 350 – Software Design Template Method Pattern Template Method Up Closer abstract class AbstractClass { final void templateMethod() { final void templateMethod() { primitiveOperation1(); primitiveOperation1(); primitiveOperation2(); primitiveOperation2(); concreteOpertation(); concreteOpertation(); hook(); hook();} abstract void primitiveOperation1(); abstract void primitiveOperation1(); abstract void primitiveOperation2(); abstract void primitiveOperation2(); void concreteOperation(); { void concreteOperation(); { //implementaiton here //implementaiton here }} The hook method does nothing, but provides an interface so that subclasses may override them, although this is not required.

CS 350 – Software Design Template Method Pattern Using the Hook public class CoffeeWithHook extends CaffeineBeverageWithHook { public void brew() { public void brew() { System.out.println(“Dripping Coffee through filter”); System.out.println(“Dripping Coffee through filter”);} public void addCondiments() { public void addCondiments() { System.out.println(“Adding Sugar and Milk”); System.out.println(“Adding Sugar and Milk”);} public boolean customerWantsCondiments() { String answer = getUserInput(); String answer = getUserInput(); if ( answer.toLowerCase().startsWith(“y”)) { if ( answer.toLowerCase().startsWith(“y”)) { return true; return true; else else return false; return false; }}

CS 350 – Software Design Template Method Pattern Using the Hook private String GetUserInput() { String answer = null; String answer = null; System.out.print(“Would you like milk and sugar with your coffee (y/n?”); System.out.print(“Would you like milk and sugar with your coffee (y/n?”); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { try { answer = in.readLine(); answer = in.readLine(); } catch (IOException ioe) { } catch (IOException ioe) { System.err.println(“IO error trying to read your answer”); System.err.println(“IO error trying to read your answer”); } if (answer = null) { if (answer = null) { return “no”; return “no”;} return answer; }

CS 350 – Software Design Template Method Pattern Sorting with the Template Method public static void sort(Object[] a) { Object aux[] = (Object[])a.clone(); Object aux[] = (Object[])a.clone(); mergeSort(aux, a, 0, a.length, 0); mergeSort(aux, a, 0, a.length, 0);} private static void mergeSort (Object src[], Object dest[], int low, int high, int off) { for (int i=low; i < high; i++) { for (int i=low; i < high; i++) { for (int j=i; j>low && for (int j=i; j>low && ((Comparable)dest[j-1]).compareTo((Comparable)dest[j])>0; j--) ((Comparable)dest[j-1]).compareTo((Comparable)dest[j])>0; j--) {swap(dest, j, j-1); {swap(dest, j, j-1); } }return;;

CS 350 – Software Design Template Method Pattern Sorting with the Template Method public class Duck implements Comparable { String name; String name; int weight; int weight; public Duck(String name, int weight) { public Duck(String name, int weight) { this.name = name; this.name = name; this.weight = weight; this.weight = weight;} public String toString() { return name + “weighs “ + weight; return name + “weighs “ + weight;} public int compareTo(Object object) { Duck otherDuck = (Duck)object; Duck otherDuck = (Duck)object; if (this.weight < otherDuck.weight) { if (this.weight < otherDuck.weight) { return -1; return -1; } else if (this.weight > otherDuck.weight) { } else if (this.weight > otherDuck.weight) { return 1; return 1; } else { return She is a witch, may we burn her? } } else { return She is a witch, may we burn her? }}}

CS 350 – Software Design Template Method Pattern Sorting with the Template Method public class DuckSortTestDrive { public static void main (String[] args) { public static void main (String[] args) { Duck[] ducks = { new Duck(“Daffy”, 8), new Duck(“Dewey”, 2), new Duck(“Howard”, 7)}; Duck[] ducks = { new Duck(“Daffy”, 8), new Duck(“Dewey”, 2), new Duck(“Howard”, 7)}; System.outprintln(“Before sorting:”); System.outprintln(“Before sorting:”); display(ducks); display(ducks); Arrays.sort(ducks); Arrays.sort(ducks); System.out.println(“\nAfter sorting:”); System.out.println(“\nAfter sorting:”); display(ducks); display(ducks);} public static void display(duck[] ducks) { for (int i = 0; i < ducks.length; i++) { for (int i = 0; i < ducks.length; i++) { System.out.println(ducks[i]); System.out.println(ducks[i]); } }}