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.

Slides:



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

Chapter 3: The Decorator Pattern
 Recent researches show that predicative programming can be used to specify OO concepts including classes, objects, interfaces, methods, single and multiple.
Behavioral Pattern: Template Method C h a p t e r 5 – P a g e 217 On occasion, two different components in a software system will have significant similarities,
Patterns Lecture 2. Singleton Ensure a class only has one instance, and provide a global point of access to it.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
ECE 355 Design Patterns Tutorial Part 2 (based on slides by Ali Razavi) Presented by Igor Ivković
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.
Informatics 122 Software Design II Lecture 6 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.
Abstraction, Inheritance, and Polymorphism in Java.
+ Informatics 122 Software Design II Lecture 9 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.
Design Patterns.
Chapter 1: Introduction to Design Patterns. SimUDuck Example.
1 GoF Template Method (pp ) GoF Strategy (pp ) PH Single User Protection (pp ) Presentation by Julie Betlach 6/08/2009.
05 - Patterns Intro.CSC4071 Design Patterns Designing good and reusable OO software is hard. –Mix of specific + general –Impossible to get it right the.
CS 210 Introduction to Design Patterns September 28 th, 2006.
CS 350 – Software Design Template Method Pattern Let’s look at two objects public class Coffee { public void prepareRecipe() { public void prepareRecipe()
An Introduction to Design Patterns. Introduction Promote reuse. Use the experiences of software developers. A shared library/lingo used by developers.
Software Engineering 1 Object-oriented Analysis and Design Applying UML and Patterns An Introduction to Object-oriented Analysis and Design and Iterative.
Design Pattern. The Observer Pattern The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all.
1 KC Web & Java – 29 november 2005 – Design Patterns – The Template Method AJAX! KC Web & Java 29 november 2005.
Patterns in programming 1. What are patterns? “A design pattern is a general, reusable solution to a commonly occurring problem in software. A design.
CS 210 Introduction to Design Patterns September 7 th, 2006.
Y2 eProjects Session 4 – Advanced Topics. Objectives  Dynamic Models  Design Patterns (Optional)  Software testing (for S4) ACCP i7.1\Sem3_4\eProject\T4.
Template Design Pattern Kalim Baig. Summary What is Template? What is Template? Definition Definition Problem Problem How might it help the designer How.
Behavioral Design Patterns Morteza Yousefi University Of Science & Technology Of Mazandaran 1of 27Behavioral Design Patterns.
1 Computer Science 340 Software Design & Testing Inheritance.
Design Patterns CSCI 5801: Software Engineering. Design Patterns.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns IX Interpreter, Mediator, Template Method recap.
CSC 205 – Java Programming II Applet. Types of Java Programs Applets Applications Console applications Graphics applications Applications are stand-alone.
CS 210 Adapter Pattern October 19 th, Adapters in real life Page 236 – Head First Design Patterns.
ECE450S – Software Engineering II
Patterns in programming1. 2 What are patterns? Answers to common design problems. A language used by developers –To discuss answers to design problems.
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Intro to Applets. Applet Applets run within the Web browser environment Applets bring dynamic interaction and live animation to an otherwise static HTML.
Programmeerimine Delphi keskkonnas MTAT Programmeerimine Delphi keskkonnas MTAT Jelena Zaitseva
DESIGN PATTERNS COMMONLY USED PATTERNS What is a design pattern ? Defining certain rules to tackle a particular kind of problem in software development.
CS 210 Final Review November 28, CS 210 Adapter Pattern.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Design Patterns Introduction
Design Patterns SE464 Derek Rayside images from NetObjectives.com & Wikipedia.
1 Chapter 5:Design Patterns. 2 What are design pattern?  Schematic description of design solution to recurring problems in software design and,  Reusable.
The Template Method Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
CSC 480 Software Engineering Design With Patterns.
CS 210 Review October 3, 2006.
Example to motivate discussion We have two lists (of menu items) one implemented using ArrayList and another using Arrays. How does one work with these.
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.
CS 210 Proxy Pattern Nov 16 th, RMI – A quick review A simple, easy to understand tutorial is located here:
Five Minute Design Patterns Doug Marttila Forest and the Trees May 30, 2009 Template Factory Singleton Iterator Adapter Façade Observer Command Strategy.
Design Patterns. Outline Purpose Purpose Useful Definitions Useful Definitions Pattern Overview Pattern Overview.
An object's behavior depends on its current state. Operations have large, multipart conditional statements that depend on the object's state.
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.
CS 210 Introduction to Design Patterns September 14 th, 2006.
Design Patterns: MORE Examples
Design Patterns: Brief Examples
Chapter 10 Design Patterns.
Chapter 5:Design Patterns
Introduction to Design Patterns
Behavioral Design Patterns
Presented by Igor Ivković
Introduction to Behavioral Patterns (3)
Object Oriented Design Patterns - Structural Patterns
OO Design Patterns - Decorator
Chapter 9 Carrano Chapter 10 Small Java
Presented by Igor Ivković
CSC 480 Software Engineering
Presentation transcript:

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 water Pour tea in cup Add lemon

package headfirst.templatemethod.simplebarista; public class Coffee { void prepareRecipe() { boilWater(); brewCoffeeGrinds(); pourInCup(); addSugarAndMilk(); } public void boilWater() { System.out.println("Boiling water"); } public void brewCoffeeGrinds() { System.out.println("Dripping Coffee through filter"); } public void pourInCup() { System.out.println("Pouring into cup"); } public void addSugarAndMilk() { System.out.println("Adding Sugar and Milk"); } package headfirst.templatemethod.simplebarista; public class Tea { void prepareRecipe() { boilWater(); steepTeaBag(); pourInCup(); addLemon(); } public void boilWater() { System.out.println("Boiling water"); } public void steepTeaBag() { System.out.println("Steeping the tea"); } public void addLemon() { System.out.println("Adding Lemon"); } public void pourInCup() { System.out.println("Pouring into cup"); }

Problems with the Solution Code is duplicated across the classes – code changes would have to be made in more than one place. Adding a new beverage would result in further duplication. Knowledge of the algorithm (i.e., the sequence of making those beverage) and implementation (how to perform each task in the algorithm) is distributed over classes.

More General Approach Both subclasses inherit a general algorithm (the sequence). Some methods in the algorithm can be concrete since those methods perform the same actions for all subclasses (boiling water and pour water). Other methods in the algorithm should be abstract, since those methods perform subclass-specific actions (brew tea or make coffee).

UML for the New Approach abstract concrete

StarBuzz Coffee Recipe void prepareRecipe() { boilWater(); brewCoffeeGrinds(); pourInCup(); addSugarAndMilk(); } Tea Recipe void prepareRecipe() { boilWater(); steepTeaBag(); pourInCup(); addLemon(); }

Abstracting Prepare Recipe

Advantages of the New Approach A single class (CaffeineBeverage) protects and controls the algorithm The superclass facilitates reuse of methods. Code changes will occur in only one place. Other beverages can be easily added.

public abstract class CaffeineBeverage { final void prepareRecipe() { boilWater(); brew(); pourInCup(); addCondiments(); } abstract void brew(); abstract void addCondiments(); void boilWater() { System.out.println("Boiling water"); } void pourInCup() { System.out.println("Pouring into cup"); } The prepareRecipe() method implements the template pattern. It serves as a template for an algorithm for making a caffeinated beverage. In the template method, each step is represented by a method. Some methods are implemented in the superclass. Other method must be implemented by the subclass and and are declared abstract.

package headfirst.templatemethod.barista; public class Coffee extends CaffeineBeverage { public void brew() { System.out.println("Dripping Coffee through filter"); } public void addCondiments() { System.out.println("Adding Sugar and Milk"); }

package headfirst.templatemethod.barista; public class Tea extends CaffeineBeverage { public void brew() { System.out.println("Steeping the tea"); } public void addCondiments() { System.out.println("Adding Lemon"); }

package headfirst.templatemethod.barista; public class BeverageTestDrive { public static void main(String[] args) { Tea tea = new Tea(); Coffee coffee = new Coffee(); System.out.println("\nMaking tea..."); tea.prepareRecipe(); System.out.println("\nMaking coffee..."); coffee.prepareRecipe(); }

Template Method Pattern Encapsulates an algorithm by creating a template for it. Defines the skeleton of an algorithm as a set of steps. Some methods of the algorithm have to be implemented by the subclasses (abstract methods in the super class). Some steps of the algorithm are concrete methods defined in the super class. The subclasses can redefine certain steps of the algorithm without changing the algorithm’s structure.

Template Pattern Structure

Code for the Template public abstract class AbstractClass { final void templateMethod() { primitiveOperation1(); primitiveOperation2(); concreteOperation(); } abstract void primitiveOperation1(); abstract void primitiveOperation2(); void concreteOperation() { //Implementation }

New issue: The customer is given an option as to whether they would like condiments or not.

package headfirst.templatemethod.barista; public abstract class CaffeineBeverageWithHook { final void prepareRecipe() { boilWater(); brew(); pourInCup(); if (customerWantsCondiments()) { addCondiments(); } abstract void brew(); abstract void addCondiments(); void boilWater() { System.out.println("Boiling water"); } void pourInCup() { System.out.println("Pouring into cup"); } boolean customerWantsCondiments() { return true; }

package headfirst.templatemethod.barista; import java.io.*; public class CoffeeWithHook extends CaffeineBeverageWithHook { public void brew() { System.out.println("Dripping Coffee through filter"); } public void addCondiments() { System.out.println("Adding Sugar and Milk"); } public boolean customerWantsCondiments() { String answer = getUserInput(); if (answer.toLowerCase().startsWith("y")) { return true; } else { return false; } private String getUserInput() { // get user response }

package headfirst.templatemethod.barista; import java.io.*; public class TeaWithHook extends CaffeineBeverageWithHook { public void brew() { System.out.println("Steeping the tea"); } public void addCondiments() { System.out.println("Adding Lemon"); } public boolean customerWantsCondiments() { String answer = getUserInput(); if (answer.toLowerCase().startsWith("y")) { return true; } else { return false; } private String getUserInput() { // get the user's response }

package headfirst.templatemethod.barista; public class BeverageTestDrive { public static void main(String[] args) { TeaWithHook teaHook = new TeaWithHook(); CoffeeWithHook coffeeHook = new CoffeeWithHook(); System.out.println("\nMaking tea..."); teaHook.prepareRecipe(); System.out.println("\nMaking coffee..."); coffeeHook.prepareRecipe(); }

Using Hooks We want to minimize the number of abstract methods used. Thus, the steps of the algorithm should not be too granular. However, less granularity means less flexibility. Hooks are methods which can be overridden by subclasses, however this is optional.

Why Hooks The number of abstract methods used must be minimized. Enables a subclass to implement an optional part of an algorithm. Enables a subclass to react to a step in the template method. Enables the subclass to make a decision for the abstract class.

Examples of Using Hooks in the Java API JFrame hooks paint() Applet hooks init() repaint() start() stop() destroy() paint()

package headfirst.templatemethod.frame; import java.awt.*; import javax.swing.*; public class MyFrame extends JFrame { public MyFrame(String title) { super(title); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(300,300); this.setVisible(true); } public void paint(Graphics graphics) { super.paint(graphics); String msg = "I rule!!"; graphics.drawString(msg, 100, 100); } public static void main(String[] args) { MyFrame myFrame = new MyFrame("Head First Design Patterns"); } JFrame has a method called update() JFrame’s update() method calls paint() method JFrame ‘s paint() method does nothing MyFrame override paint() method to do something Paint() is a hook!

package java.applet; import java.awt.*; import java.awt.image.ColorModel; import java.net.URL; import java.net.MalformedURLException; import java.util.Hashtable; import java.util.Locale; public class Applet extends Panel { // other methods of the Applet class … … public void init() { } public void start() { } public void stop() { } public void destroy() { }

package headfirst.templatemethod.applet; import java.applet.Applet; import java.awt.Graphics; public class MyApplet extends Applet { String message; public void init() { message = "Hello World, I'm alive!"; repaint(); } public void start() { message = "Now I'm starting up..."; repaint(); } public void stop() { message = "Oh, now I'm being stopped..."; repaint(); } public void destroy() { message = "Goodbye, cruel world"; repaint(); } }

Hollywood Principle Principle: Don’t call us, we will call you. Low-level components are activated by high- level components. A low-level component never calls a high-level component. In the template pattern the abstract class is the high-level component and the concrete classes the low-level components.

In Summary… Design Principle: Don’t call us we’ll call you. Template pattern defines steps of an algorithm. Subclasses cannot change the algorithm - final Facilitates code reuse. Similar to the strategy pattern.

In Summary… Design Principle: Don’t call us we’ll call you. Template pattern defines steps of an algorithm. Subclasses cannot change the algorithm - final Facilitates code reuse. Similar to the strategy pattern. The factory pattern is a specialization of the template pattern.

Summary so far.. OO Basics Abstraction Encapsulation Inheritance Polymorphism OO Principles Encapsulate what varies Favor composition over inheritance Program to interfaces not to implementations Strive for loosely coupled designs between objects that interact Classes should be open for extension but closed for modification. Depend on abstracts. Do not depend on concrete classes. Only talk to your friends Hollywood principles: don’t call us, we will call you.

Summary so far… OO Patterns Strategy Pattern defines a family of algorithms, Encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically. Decorator Pattern – attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative for sub-classing for extending functionality Singleton Pattern – ensure a class only has one instance, and provide a global point of access to it The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. The Façade Pattern provides a unified interface to a set of interfaces in a subsystem. Façade defines a higher level interface that makes the subsystem easier to use. The Template Pattern defines steps of an algorithm. Subclasses cannot change the algorithm (final). It facilitates code reuse.