Slides adapted from Alex Mariakakis, with material from David Mailhot, Hal Perkins, Mike Ernst Section 9: Design Patterns.

Slides:



Advertisements
Similar presentations
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Encapsulation, toString reading: self-checks: #13-18,
Advertisements

Singleton vs utility class  at first glance, the singleton pattern does not seem to offer any advantages to using a utility class  i.e., a utility class.
Slides by Alex Mariakakis with material from David Mailhot, Hal Perkins, Mike Ernst Section 9: Design Patterns.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
Design Patterns CS is not simply about programming
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Proxy Design Pattern Source: Design Patterns – Elements of Reusable Object- Oriented Software; Gamma, et. al.
Programming Languages and Paradigms Object-Oriented Programming.
Design Patterns.
Writing Classes (Chapter 4)
JavaONE Kjartan Aanestad (Objectware)1 JavaONE 2007.
1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Singleton, Memento, Flyweight.
Chapter 26 GoF Design Patterns. The Adapter Design Pattern.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Dependency Injection Technion – Institute of Technology Author: Gal Lalouche - Technion 2015 ©
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
The Factory Patterns SE-2811 Dr. Mark L. Hornick 1.
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
Patterns in programming1. 2 What are patterns? Answers to common design problems. A language used by developers –To discuss answers to design problems.
Factory Method Explained. Intent  Define an interface for creating an object, but let subclasses decide which class to instantiate.  Factory Method.
CSE 331 Software Design & Implementation Hal Perkins Winter 2012 Design Patterns Part 2 (Slides by Mike Ernst and David Notkin) 1.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
The Singleton Pattern SE-2811 Dr. Mark L. Hornick 1.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
DESIGN PATTERNS COMMONLY USED PATTERNS What is a design pattern ? Defining certain rules to tackle a particular kind of problem in software development.
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 (part 2) CSE 331 University of Washington.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
Design Patterns Introduction
Design Patterns SE464 Derek Rayside images from NetObjectives.com & Wikipedia.
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.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
1 CSE 331 Design Patterns 1: Iterator, Adapter, Singleton, Flyweight slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin,
The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1.
Proxy Pattern defined The Proxy Pattern provides a surrogate or placeholder for another object to control access to it by creating a representative object.
The Singleton Pattern (Creational)
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
CSC 205 Programming II Lecture 4 Abstract Class. The abstract keyword indicate that a class is not instantiable Defining a type which will be specialized.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
Section 9: Design Patterns
MPCS – Advanced java Programming
Design Patterns C++ Java C#.
Low Budget Productions, LLC
Factory Patterns 1.
Design Patterns C++ Java C#.
CSE 331 Software Design & Implementation
Section 9: Design Patterns
Section 9: Design Patterns
Advanced Programming Behnam Hatami Fall 2017.
Section 8: Design Patterns
Singleton Pattern Pattern Name: Singleton Pattern Context
Building Java Programs
Section 9: Design Patterns
Section 9: Design Patterns
CS 350 – Software Design Singleton – Chapter 21
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Section 9: Design Patterns
GoF Patterns Ch. 26.
Presentation transcript:

Slides adapted from Alex Mariakakis, with material from David Mailhot, Hal Perkins, Mike Ernst Section 9: Design Patterns

Agenda What are design patterns? Creational patterns review Structural patterns preview

What Is A Design Pattern A standard solution to a common programming problem A technique for making code more flexible Shorthand for describing program design and how program components are connected

Creational Patterns Problem: Constructors in Java are not flexible Always return a fresh new object, never reuse one Can’t return a subtype of the class they belong to Solution: Creational patterns! Sharing Singleton Interning Flyweight Factories Factory method Factory object Builder (new!)

Creational Patterns: Sharing The old way: Java constructors always return a new object Singleton: only one object exists at runtime Factory method returns the same object every time Interning: only one object with a particular (abstract) value exists at runtime Factory method returns an existing object, not a new one Flyweight: separate intrinsic and extrinsic state, represents them separately, and interns the intrinsic state Implicit representation uses no space Not as common/important

Creational Patterns: Singleton For a class where only one object of that class can ever exist Two possible implementations Eager instantiation: creates the instance when the class is loaded to guarantee availability Lazy instantiation: only creates the instance once it’s needed to avoid unnecessary creation

Creational Patterns: Singleton Eager instantiation public class Bank { private static Bank INSTANCE = new Bank(); // private constructor private Bank() { … } // factory method public static Bank getInstance() { return INSTANCE; } Bank b = new Bank(); Bank b = Bank.getInstance();

Creational Patterns: Singleton Lazy instantiation public class Bank { private static Bank INSTANCE; // private constructor private Bank() { … } // factory method public static Bank getInstance() { if (INSTANCE == null) { INSTANCE = new Bank(); } return INSTANCE; } Bank b = new Bank(); Bank b = Bank.getInstance();

Creational Patterns: Singleton Would you prefer eager or lazy instantiation for an HTTPRequest class? handles authentication definitely needed for any HTTP transaction Would you prefer eager or lazy instantiation for a Comparator class? compares objects may or may not be used at runtime

Creational Patterns: Interning Similar to Singleton, except instead of just having one object per class, there’s one object per abstract value of the class Saves memory by compacting multiple copies Requires the class being interned to be immutable. Why?

Creational Patterns: Interning public class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; public String toString() { return “(” + x + “,” + y + “)”; }

Creational Patterns: Interning public class Point { private static Map instances = new WeakHashMap (); public static Point getInstance(int x, int y) { String key = x + “,”, + y; if (!instances.containsKey(key)) instances.put(key, new Point(x,y)); return instances.get(key); } private final int x, y; // immutable private Point(int x, int y) {…} } If our point was represented with r and theta, we’d need to constrain them for use in the key. Otherwise, we’d have “5, pi” and “5, 3pi” as different entries in our map even though they are the same abstract value.

Creational Patterns: Factories public class City { public Stereotype getStereotypicalPerson() {…} } City seattle = new City(); seattle.getSterotypicalPerson(); // we want a SeattleStereotype

Creational Patterns: Factories Factories solve the problem that Java constructors cannot return a subtype of the class they belong to Two options: Factory method Helper method creates and returns objects Method defines the interface for creating an object, but defers instantiation to subclasses Factory object Abstract superclass defines what can be customized Concrete subclass does the customization, returns appropriate subclass Object provides the interface for creating families of related/dependent objects without specifying their concrete classes

Creational Patterns: Factory Method public class City { public Stereotype getStereotypicalPerson() {…} } public class Seattle extends City public Stereotype getStereotypicalPerson() { return new SeattleStereotype(); } City seattle = new Seattle(); seattle.getSterotypicalPerson();

Creational Patterns: Factory Object interface StereotypeFactory { Stereotype getStereotype(); } class SeattleStereotypeFactory implements StereotypeFactory { public Stereotype getStereotype() { return new SeattleStereotype(); } public class City { public City(StereotypeFactory f) {…} public Stereotype getStereotypicalPerson() { f.getStereotype(); } City seattle = new City(new SeattleStereotypeFactory()); seattle.getSterotypicalPerson();

Creational Patterns: Builder The class has an inner class Builder and is created using the Builder instead of the constructor The Builder takes optional parameters via setter methods (e.g., setX(), setY(), etc.) When the client is done supplying parameters, she calls build() on the Builder, finalizing the builder and returning an instance of the object desired

Creational Patterns: Builder public class NutritionFacts { // required private final int servingSize, servings; // optional private final int calories, fat, sodium; public NutritionFacts(int servingSize, int servings) { this(servingSize, servings, 0); } public NutritionFacts(int servingSize, int servings, int calories) { this(servingSize, servings, calories, 0); } public NutritionFacts(int servingSize, int servings, int calories, int fat) { this(servingSize, servings, calories, fat, 0); } … public NutritionFacts(int servingSize, int servings, int calories, int fat, int sodium) { this.servingSize = servingSize; this.servings = servings; this.calories = calories; this.fat = fat; this.sodium = sodium; }

Creational Patterns: Builder public class NutritionFacts { private final int servingSize, servings, calories, fat, sodium; public static class Builder { // required private final int servingSize, servings; // optional, initialized to default values private final int calories = 0; private final int fat = 0; private final int sodium = 0; public Builder(int servingSize, int servings) { this.servingSize = servingSize; this.servings = servings; } public Builder calories(int val) { calories = val; return this; } public Builder fat(int val) { fat = val; return this; } public Builder sodium(int val) { sodium = val; return this; } public NutritionFacts build() { return new NutritionFacts(this); } } public NutritionFacts(Builder builder) { this.servingSize = builder.servingSize; this.servings = builder.servings; this.calories = builder.calories; this.fat = builder.fat; this.sodium = builder.sodium; }

Creational Patterns: Builder Useful when you have many constructor parameters It is hard to remember which order they should all go in Easily allows for optional parameters If you have n optional parameters, you need 2^n constructors, but only one builder

Structural Patterns Problem: Sometimes difficult to realize relationships between entities Important for code readability Solution: Structural patterns! We’re just going to talk about wrappers, which translate between incompatible interfaces PatternFunctionalityInterfacePurpose Adaptersamedifferentmodify the interface Decoratordifferentsameextend behavior Proxysame restrict access

Structural Patterns: Adapter Changes an interface without changing functionality Rename a method Convert units Why? We already have a class that does most/all what we want It just doesn’t do it in the form we want

Structural Patterns: Adapter MSR has a library and API for image composition public void photoComposite(List photoStack, List objectives, Image output); MS PhotoGallery wants to use this API to make new features PhotoGalleryDisplay object contains a DisplayImage that is a 2d array of pixels representing the main image in view Both codebases are very large and changes will affect a lot of other pieces

Structural Patterns: Adapter public class PhotoSynthAdapter { public DisplayImage makePanoramic(List photos) { Image output = new Image(); List objectives = generatePanoWeights(); photoComposite(photos, objectives, output); return ImageToDisplayImage(output); } public DisplayImage removeTourists(…) … }

Structural Patterns: Adapter Other examples: Angles passed in using radians vs. degrees Bytes vs. strings Hex vs. decimal numbers

Structural Patterns: Decorator Adds functionality without changing the interface Add caching Adds to existing methods to do something additional while still preserving the previous spec Add logging Decorators can remove functionality without changing the interface UnmodifiableList with add() and put()

public abstract class Cake{ public abstract double getWeight(); public abstract String getDescription(); } public class PlainCake extends Cake{ public double getWeight() { return 8.0; } public String getDescription() { return “sponge cake”; } from

public abstract class CakeDecorator extends Cake { protected final Cake decoratedCake; protected String separator = ", "; public CakeDecorator (Cake decoratedCake) { this.decoratedCake = decoratedCake; } public double getWeight() { return decoratedCake.getWeight(); } public String getDescription() { return decoratedCake.getDescription(); } from

class Frosting extends CakeDecorator { public Frosting (Cake decoratedCake) { public double getWeight() { return super.getWeight() + 4.0; } public String getDescription() { return super.getDescription + separator + “vanilla frosting”; } from

public static void main(String[] args) { Cake c = new PlainCake(); System.out.println(“Weight: " + c.getWeight() + "; Contains: " + c.getDescription()); c = new Frosting(c); System.out.println(“Weight: " + c.getWeight() + "; Contains: " + c.getDescription()); … c = new Roses(c); … } Weight: 8.0 Contains: sponge cake Weight: 12.0 Contains: sponge cake, vanilla frosting Weight: 15.5 Contains: sponge cake, vanilla frosting, buttercream roses from

Structural Patterns: Proxy Wraps the class while maintaining the same interface and same functionality Integer vs. int, Boolean vs. boolean Controls access to other objects Communication: manage network details when using a remote object Security: permit access only if proper credentials Creation: object might not yet exist because creation is expensive