Informatics 122 Software Design II Lecture 6 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.

Slides:



Advertisements
Similar presentations
Informatics 122 Software Design II Lecture 5 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.
Advertisements

Patterns Lecture 2. Singleton Ensure a class only has one instance, and provide a global point of access to it.
Design Patterns CS is not simply about programming
Abstract Classes and Interfaces
Design Patterns academy.zariba.com 1. Lecture Content 1.What are Design Patterns? 2.Creational 3.Structural 4.Behavioral 5.Architectural 6.Design Patterns.
+ Informatics 122 Software Design II Lecture 8 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.
What Is a Factory Pattern?.  Factories are classes that create or construct something.  In the case of object-oriented code languages, factories construct.
Creational Patterns Making Objects The Smart Way Brent Ramerth Abstract Factory, Builder.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. The Façade Design Pattern (1) –A structural design pattern.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. The Factory Method Design Pattern (1) –A creational design.
+ Informatics 122 Software Design II Lecture 9 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Design Patterns.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Design patterns. What is a design pattern? Christopher Alexander: «The pattern describes a problem which again and again occurs in the work, as well as.
CS 350 – Software Design Template Method Pattern Let’s look at two objects public class Coffee { public void prepareRecipe() { public void prepareRecipe()
SOFTWARE DESIGN AND ARCHITECTURE
CSSE 374: Introduction to Gang of Four Design Patterns
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
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.
CSC 211 Introduction to Design Patterns. Intro to the course Syllabus About the textbook – Read the introduction and Chapter 1 Good attendance is the.
Patterns in programming 1. What are patterns? “A design pattern is a general, reusable solution to a commonly occurring problem in software. A design.
Refactoring Improving the structure of existing code Refactoring1.
The Adapter Pattern SE-2811 Dr. Mark L. Hornick 1.
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.
CS 210 Adapter Pattern October 19 th, Adapters in real life Page 236 – Head First Design Patterns.
Unit 4 Object-Oriented Design Patterns NameStudent Number CAI XIANGHT082182A KYAW THU LINHT082238Y LI PENGFEIHT082220L NAUNG NAUNG LATTHT082195L PLATHOTTAM.
Patterns in programming1. 2 What are patterns? Answers to common design problems. A language used by developers –To discuss answers to design problems.
Object Oriented Software Development
Creational Pattern: Factory Method At times, a framework is needed to standardize the behavior of objects that are used in a range of applications, while.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Software Design Patterns Curtsy: Fahad Hassan (TxLabs)
Design Patterns David Talby. This Lecture Re-routing method calls Chain of Responsibility Coding partial algorithms Template Method The Singleton Pattern.
Interfaces About Interfaces Interfaces and abstract classes provide more structured way to separate interface from implementation
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.
More Design Patterns From: Shalloway & Trott, Design Patterns Explained, 2 nd ed.
CS212: Object Oriented Analysis and Design Lecture 38: Design Pattern-II.
Design Patterns Introduction
Design Patterns SE464 Derek Rayside images from NetObjectives.com & Wikipedia.
JAVA DESIGN PATTERN Structural Patterns - Facade Pattern Presented by: Amit kumar narela Ise Ise
Advanced Object-oriented Design Patterns Creational Design Patterns.
Refactoring1 Improving the structure of existing code.
Watching the movie the hard way…. Page 256 – Head First Design Patterns.
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 350 – Software Design The Adapter Pattern – Chapter 7 Gang of Four Definition: Convert the interface of a class into another interface that the client.
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
CS 350 – Software Design The Facade Pattern – Chapter 6 Many design patterns are catalogued in the “Gang of Four” text. I find their definitions not to.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
Chapter 10 Design Patterns.
MPCS – Advanced java Programming
Design Patterns Lecture part 2.
Low Budget Productions, LLC
Behavioral Design Patterns
Facade Pattern Jim Fawcett CSE776 – Design Patterns Summer 2010
Advanced Programming Behnam Hatami Fall 2017.
Introduction to Behavioral Patterns (3)
Informatics 122 Software Design II
Object Oriented Design Patterns - Creational Patterns
Improving the structure of existing code
CS 350 – Software Design Singleton – Chapter 21
Design pattern Lecture 6.
Software Design Lecture : 35.
Informatics 122 Software Design II
Designing For Testability
Presentation transcript:

Informatics 122 Software Design II Lecture 6 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission of the professor is prohibited. 1 Portions of the slides in this lecture are adapted from lectures/

Today’s Lecture Design patterns – part 3 of a 3-part series Three patterns: Template Method Singleton Facade Assignment 3, part 1 2

Template Method: Definition The Template Method pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure Template Method defines the steps of an algorithm and allows subclasses to provide the implementation for one or more steps Makes the algorithm abstract Each step of the algorithm is represented by a method Encapsulates the details of most steps Steps (methods) handled by subclasses are declared abstract Shared steps (concrete methods) are placed in the same class that has the template method, allowing for code re-use among the various subclasses

Template Method: Structure

Example: Tea and Coffee Consider an example in which we have recipes for making tea and coffee at a coffee shop Coffee Boil water Brew coffee in boiling water Pour coffee in cup Add sugar and milk Tea Boil water Steep tea in boiling water Pour tea in cup Add lemon

Coffee Implementation 6

Tea Implementation 7

Code Duplication! We have code duplication occurring in these two classes boilWater() and pourInCup() are exactly the same Let’s get rid of the duplication

Similar Algorithms The structure of the algorithms in prepareRecipe() is similar for Tea and Coffee We can improve our code further by making the code in prepareRecipe() more abstract brewCoffeeGrinds() and steepTea() -> brew() addSugarAndMilk() and addLemon() -> addCondiments() Now all we need to do is specify this structure in CaffeineBeverage.prepareRecipe() and make sure we do it in such a way so that subclasses can’t change the structure By using the word “final” (see next slide)

Caffeine Beverage Implementation Note: use of final keyword for prepareRecipe() brew() and addCondiments() are abstract and must be supplied by subclasses boilWater() and pourInCup() are specified and shared across all subclasses

Coffee and Tea Implementations 11 Nice and simple!

What have we done? Took two separate classes with separate but similar algorithms Noticed duplication and eliminated it by adding a superclass Made steps of algorithm more abstract and specified its structure in the superclass Thereby eliminating another “implicit” duplication between the two classes Revised subclasses to implement the abstract (unspecified) portions of the algorithm… in a way that made sense for them

House Builder Example

Singleton Pattern Used to ensure that only one instance of a particular class ever gets created and that there is just one (global) way to gain access to that instance Let’s derive this pattern by starting with a class that has no restrictions on who can create it

Deriving Singleton (I) public class Ball { private String color; public Ball (String color) { this.color = color; } public void bounce() { System.out.println(“boing!”); } } Ball b1 = new Ball (“red”); Ball b2 = new Ball (“blue”); b1.bounce(); b2.bounce();

Problem: Universal Instantiation As long as a client object “knows about” the name of class Ball, it can create instances of Ball Ball b1 = new Ball (“orange”); This is because the constructor is public We can stop unauthorized creation of Ball instances by making the constructor private

Deriving Singleton (II) public class Ball { private String color; private Ball(String color) { this.color = color; } public void bounce() { System.out.println (“boing!”); } } // next line now impossible by any method outside of Ball Ball b2 = new Ball (“red”);

Problem: No Point of Access! Now that the constructor is private, no class can gain access to instances of Ball But our requirements were that there would be at least one way to get access to an instance of Ball We need a method to return an instance of Ball But since there is no way to get access to an instance of Ball, the method CANNOT be an instance method This means it needs to be a class method, aka a static method

Deriving Singleton public class Ball { private String color; private Ball (String color) { this.color = color; } public void bounce() { System.out.println (“boing!”); } public static Ball getInstance (String color) { return new Ball (color); }

Problem: Back to Universal Instantiation We are back to this problem where any client can create an instance of Ball; instead of saying this: Ball b1 = new Ball (“blue”); they just say Ball b1 = Ball.getInstance (“blue”); Need to ensure only one instance is ever created Need a static variable to store that instance

Deriving Singleton (IV) public class Ball { private static Ball ball; private String color; private Ball (String color) { this.color = color; } public void bounce () { System.out.println(“boing!”); } public static Ball getInstance(String color) { return ball; }

Problem: No instance! Now the getInstance() method returns null each time it is called Need to check the static variable to see if it is null If so, create an instance Otherwise return the single instance

Deriving Singleton (V) public class Ball { private static Ball ball; private String color; private Ball (String color) { this.color = color;} public void bounce() { System.out.println(“boing!”); } public static Ball getInstance (String color) { if (ball == null) { ball = new Ball(color); } return ball; }

Problem: First Parameter Wins The code on the previous slide shows the Singleton pattern private constructor private static variable to store the single instance public static method to gain access to that instance this method creates object if needed; returns it ensures that only one instance of Ball is ever created But what if you want only one instance of each color? This code ignores the fact that a parameter is being passed in; so if a “red” ball is created all subsequent requests for a “green” ball are ignored

Solution: Use a Map The solution to the final problem is to change the private static instance variable to a Map private Map ballRecord = new HashMap… Then check if the map contains an instance for a given value of the parameter this ensures that only one ball of a given color is ever created this is a very acceptable variation of the Singleton pattern public static Ball getInstance(String color) { if (!ballRecord.containsKey(color)) { ballRecord.put(color, new Ball(color)); } return ballRecord.get(color); }

Singleton Pattern: Structure Singleton involves only a single class (not typically called Singleton). That class is a full-fledged class with other attributes and methods (not shown). The class has a static variable that points at a single instance of the class. The class has a private constructor (to prevent other code from instantiating the class) and a static method that provides access to the single instance.

Singleton Pattern: Real World Examples Centralized manager of resources Window manager File system manager … Logger classes Factories Especially those that issue IDs Singleton is often combined with Factory Method and Abstract Factory patterns

Façade (I) “Provide 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.” Design Patterns, Gang of Four, 1995 There can be significant benefit in wrapping a complex subsystem with a simplified interface If you don’t need the advanced functionality or fine- grained control of the former, the latter makes life easy

Façade Pattern: Structure

Façade (II) Façade works best when you are accessing a subset of the system’s functionality You can add new features by adding them to the Façade (not the subsystem); you still get a simpler interface Façade not only reduces the number of methods you are dealing with but also the number of classes Imagine having to pull Employees out of Divisions that come from Companies that you pull from a Database A Façade in this situation can fetch Employees directly

Example (Without a Façade) Without a Façade, Client contacts the Database to retrieve Company objects. It then retrieves Division objects from them and finally gains access to Employee objects. It uses four classes.

Example (With a Façade) With a Façade, the Client is shielded from most of the classes. It uses the Database Façade to retrieve Employee objects directly.

Façade Example (I) Imagine a library of classes with a complex interface and/or complex interrelationships Home Theater System Amplifier, DvdPlayer, Projector, CdPlayer, Tuner, Screen, PopcornPopper, and TheatreLights each with its own interface and interclass dependencies

Façade Example (II) Imagine steps for “watch movie” turn on popper, make popcorn, dim lights, screen down, projector on, set projector to DVD, amplifier on, set amplifier to DVD, DVD on, etc. Now imagine resetting everything after the movie is done, or configuring the system to play a CD, or play a video game, etc.

Façade Example (III) For this example, we can place high level methods… like “watch movie”, “reset system”, “play cd” … in a façade object and encode all of the steps for each high level service in the façade; Demo Client code is simplified and dependencies are reduced A façade not only simplifies an interface, it decouples a client from a subsystem of components Indeed, Façade lets us encapsulate subsystems, hiding them from the rest of the system

Façade vs. Adapter Comparison (I) To many people, these two patterns (Adapter/Façade) appear to be similar They both act as wrappers of a preexisting class They both take an interface that we don’t want and convert it to an interface that we can use With Façade, the intent is to simplify the existing interface With Adapter, we have a target interface that we are converting to In addition, we often want the adapter to plug into an existing framework and behave polymorphically

Façade vs. Adapter Comparison (II) Superficial difference Façade hides many classes Adapter hides only one But a Façade can simplify a single, very complex object an adapter can wrap multiple objects at once in order to access all the functionality it needs The key is simplify (façade) vs. convert (adapter)

More Information on Design Patterns… Patterns Interaction design patterns Anti-Patterns And numerous, numerous, numerous books and other online sources

Assignment 3, part 1

Next Time Refactoring Assignment 3, part 2