1 Pattern-Oriented Design by Rick Mercer based on the GoF book and Design Patterns Explained A New Perspective on Object-Oriented Design Alan Shalloway,

Slides:



Advertisements
Similar presentations
Welcome to. Who am I? A better way to code Design Patterns ???  What are design patterns?  How many are there?  How do I use them?  When do I use.
Advertisements

Design Patterns Introduction What is a Design Pattern? Why were they developed? Why should we use them? How important are they?
Design Patterns CMPS Design Patterns Consider previous solutions to problems similar to any new problem ▫ must have some characteristics in common.
OOP Design Patterns Chapters Design Patterns The main idea behind design patterns is to extract the high level interactions between objects and.
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
Design Patterns Copyright © Vyacheslav Mukhortov, Nikita Nyanchuk-Tatarskiy, Copyright © INTEKS LLC,
Plab – Tirgul 12 Design Patterns
1 Software Testing and Quality Assurance Lecture 12 - The Testing Perspective (Chapter 2, A Practical Guide to Testing Object-Oriented Software)
Software Testing and Quality Assurance
7M701 1 Class Diagram advanced concepts. 7M701 2 Characteristics of Object Oriented Design (OOD) objectData and operations (functions) are combined 
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
PRESENTED BY SANGEETA MEHTA EECS810 UNIVERSITY OF KANSAS OCTOBER 2008 Design Patterns.
Design Patterns academy.zariba.com 1. Lecture Content 1.What are Design Patterns? 2.Creational 3.Structural 4.Behavioral 5.Architectural 6.Design Patterns.
Chapter 26 Applying Gang of Four Design Patterns 1CS6359 Fall 2012 John Cole.
CERN – European Organization for Nuclear Research GS Department – Administrative Information Services Design Patterns in Groovy Nicolas Décrevel Advanced.
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
Object Oriented Software Development
Design Patterns.
Design Dan Fleck CS 421 George Mason University. What is the design phase? Analysis phase describes what the system should do Analysis has provided a.
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.
CSSE 374: Introduction to Gang of Four Design Patterns
An Introduction to Design Patterns. Introduction Promote reuse. Use the experiences of software developers. A shared library/lingo used by developers.
CS 4240: More Design Patterns Readings: Chap. 9. Let’s Recap Some Ideas and Strategies We’ll assume some design-planning is useful up-front Design with.
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.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
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 350 – Software Design The Strategy Pattern – Chapter 9 Changes to software, like other things in life, often focus on the immediate concerns and ignore.
Design Patterns CSCI 5801: Software Engineering. Design Patterns.
GRASP: Designing Objects with Responsibilities
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.
Chapter 8 Object Design Reuse and Patterns. Object Design Object design is the process of adding details to the requirements analysis and making implementation.
Patterns in programming1. 2 What are patterns? Answers to common design problems. A language used by developers –To discuss answers to design problems.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VIII Chain of Responsibility, Strategy, State.
CS 4233 Review Feb February Review2 Outline  Previous Business – My.wpi.edu contains all grades to date for course – Review and contact.
CSC 313 – Advanced Programming Topics. What Is the Factory Method?  Creation details hidden by AbstractCreator  Does effective job of limiting concrete.
Design Patterns. OO-Concepts Don’t rewrite code Encapsulation Inheritance Write flexible code.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Design Patterns David Talby. This Lecture Re-routing method calls Chain of Responsibility Coding partial algorithms Template Method The Singleton Pattern.
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.
The Strategy Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
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.
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:
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.
Five Minute Design Patterns Doug Marttila Forest and the Trees May 30, 2009 Template Factory Singleton Iterator Adapter Façade Observer Command Strategy.
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.
Design Patterns: MORE Examples
Design Patterns: Brief Examples
Chapter 10 Design Patterns.
MPCS – Advanced java Programming
Chapter 12: Collaboration Diagram - PART2
Introduction to Design Patterns
CS 350 – Software Design The Strategy Pattern – Chapter 9
Chapter Nine The Strategy Pattern
Behavioral Design Patterns
object oriented Principles of software design
Software Engineering Lecture 7 - Design Patterns
Pattern-Oriented Design
CS 350 – Software Design Singleton – Chapter 21
Informatics 122 Software Design II
GoF Patterns Ch. 26.
Presentation transcript:

1 Pattern-Oriented Design by Rick Mercer based on the GoF book and Design Patterns Explained A New Perspective on Object-Oriented Design Alan Shalloway, James R. Trott Addison Wesley ISBN CSC 335: Object-Oriented Programming and Design

2 Using Patterns to Design  There are 23 Object-Oriented design patterns cataloged in the GoF book--we’ve considered 10 so far (Fall 09)  Iterator, Observer, Strategy, Composite, Singleton, Flyweight, Command, Template, Chain of Responsibility, Decorator  We'll use some patterns to help design a system  The new case study is in electronic retailing over the internet (An Ecommerce system)  Several design decisions will be aided by knowledge of existing design patterns  at a fairly high level of abstraction

3 Plan too much, plan ahead, or don’t plan at all?  Development of software systems can suffer from analysis paralysis: attempt to consider all possible changes in the future  At other times developers jump to code too quickly  there is tremendous pressure to deliver, not maintain  Life’s three certainties for software developers  Death, Taxes, and Changes in Requirements  There is a middle ground for planning for change

4 How will change occur  First, anticipate that changes will occur  Consider where they will change, rather than the exact nature of the changes  These issues will come up in the Ecommerce case study

5 What is variable in the design?  Consider what is variable in your design  Instead of focusing on what might force a change to your design  Consider what you might want to change  Encapsulate the concept that varies –this is a theme of many design patterns  Hopefully there are long term benefits without a lot of extra work up front

6 OO Design Patterns Used  In the upcoming case study, these design patterns will help make for a system that is good design  Strategy  Singleton  Decorator  Observer  We've considered all four

7 An Ecommerce System  There is a TaskController object that handles sales requests over the internet  When the sales order is requested, the controller delegates to a SalesOrder object

8 Assign Responsibilities  SalesOrder responsibilities:  Allow users to make an order using GUI input  Process the order  Print a sales receipt

9 Changing Requirements  Start charging taxes on order from customers  need to add rules for taxation, but how?  modify existing SalesOrder to handle U.S. taxes  extend the existing SalesOrder object and modify the tax rules so it applies to the new country  This is an inheritance solution

10 Subclassing Solution TaskController CanadianSalesOrder +calcTax():double SalesOrder +calcTax():double SalesTicketPrinter Canadian Tax Rules US Tax Rules

11 Favor Composition Over Inheritance  Design pattern theme of composition over inheritance is ignored in previous design  Here is a different approach  consider what is variable in the design  encapsulate the concept the varies  Accept the fact that tax rules vary country to country and state to state and county to county, and sometimes city to city (like in Arizona) and they change

12 Alternate Designs  Or use an abstract class with an abstract double calcTax() and many classes in a hierarchy  Or design an interface to be implemented by different classes using different algorithms  Then have SalesOrder contain a reference to the correct object (composition over inheritance) public interface TaxCalculator { // A Salable object knows price and how it is taxed public double taxAmount(Salable itemSold, double quantity); }

13 A Better Design with Strategy

14 Why does Strategy make this design better?  Better Cohesion (hangs together)  sales tax details are in its own class  Easy to add tax rules from different countries  Easier to shift responsibilities  In the first design where CanadianSalesOrder extends USSalesOrder, only TaskController is able to determine which type of sales order to use  With Strategy, either TaskController or SalesOrder could set the TaxCalculator

15 Determine What Varies  What Varies?  The business rules for taxation  Current design handles variations at least as well as the other design design  Current design will handle future variations as well  A family of tax calculation algorithms have been encapsulated as objects, they are interchangeable,  Strategy pattern applied in an Ecommerce system

16 Using the Strategy Pattern  What happens when EnglishTaxer is added  In England, old-age pensioners are not required to pay taxes on sales items  How can this be handled? 1) Pass age of the Customer to TaxCalculator object 2) Be more general and pass a Customer object 3) Be even more general and pass a reference to the SalesOrder object (this) to the TaxCalculator and let that EnglishStrategy object ask SalesOrder for customer age (post some html to the client)

17 Is this change bad?  To handle this new requirement, SalesOrder and TaxCalculator have to be modified  But the change is small and certainly doable  Not likely to cause a new problem  If a Strategy needs more information, pass the information to the object as an argument  Some objects may ignore the extra parameter  Strategy can be applied anywhere you hear this  "At different times, different rules apply"

18 Singleton Pattern  Singleton Ensure a class only has one instance and provide a global point of access to it  The singleton pattern works by having a special method that is used to instantiate the object  when called, the method checks to see if the object has already been instantiated  it returns the singleton if instantiated or constructs a new one if this is the first call to get the instance  to guarantee this, have a private constructor

19 Using Singleton  TaxCalculators are currently encapsulated as Strategy objects  How many USTaxer objects are required in this system? How many CanadianTaxers?  Forces:  The same object is being used over and over again  More efficient to avoid instantiating them and throwing them away again and again  Doing all at once could be slow to start up  Could instantiate these objects as needed

20 Only want one when needed  Don’t need more than one instance of each TaxCalculator class  Solution:  Let Strategy objects handle the instantiation  Let there be only one instance  Don’t concern clients (SalesOrder) over this detail  In other words, use the Singleton design pattern

21 USTaxer is now a Singleton public class USTaxer implements TaxCalculator { private static USTaxer instance; // Only one private static double taxRate; private USTaxer() { taxRate = 0.06; // greatly simplified } public static USTaxer getInstance() { if (instance == null) instance = new USTaxer(); return instance; } public double taxAmount(Salable item, double quan) { return 0; // TODO: Implement tax algorithm }

22 composition aggregation (Salable is one part of SalesOrder) dependency implements

23 Aggregation vs. Composition Definitions from the Unified Modeling Language Guide  Aggregation A special form of association that specifies a whole/part relationship between the aggregate (the whole) and a component (the part)  When a class has an instance variable  Composition A form of aggregation with strong ownership. Once a component is created, its lives and dies with its whole  A TaxCalculator object is only necessary with a SalesOrder not used elsewhere

24 Other Patterns applied  In the Ecommerce system, we will now  “Decorate” a SalesTicket and  “Observe” a Customer

25 Decorate SalesTicketPrinter  Assume the SalesTicketPrinter currently creates an html sales receipt Airline Ticket  New Requirement: Add header with company name, add footer that is an advertisement, during the holidays add holiday relevant header(s) and footer(s), we’re not sure how many  One solution  Place control in SalesTicketPrinter  Then you need flags to control what header(s) get printed

26 One Solution  This works well if there are few header and footer options or perhaps just add a few private helper methods underline indicates static methods

27 Strategy Pattern?  If there are many types of headers and footers, with only one being printed each time, use Strategy  If there are more than one header and footer, and the ordering changes, and the number of combinations grows,  use the Decorator design pattern to chain together the desired functionality in the correct order needed

28 Decorator Again  Decorator summary repeated Attach additional Responsibilities to an object dynamically  GoF book states: Decorators provide a flexible alternative to subclassing for functionality  Start chain with decorators, end with original object Decorator 1 Decorator 2 Concrete Component Example: keyboard = new BufferedReader( new InputStreamReader( System.in));

29

30 A Simple SalesTicket abstract class Component { abstract public void printTicket(); } // Instances of this class are sales tickets // that may be decorated class SalesTicket extends Component public void printTicket() { // Hard coded here, but simpler than // adding a new Customer class... System.out.println("Customer: Kim"); System.out.println("The sales ticket itself"); System.out.println("Total: $123.45"); }

31 TicketDecorator abstract class TicketDecorator extends Component { private Component myComponent; public TicketDecorator() { myComponent = null; } public TicketDecorator(Component c) { myComponent = c; public void printTicket() { if (myComponent != null) myComponent.printTicket(); }

32 A Header Decorator class HeaderDecorator1 extends TicketDecorator { public HeaderDecorator1(Component c) { super(c); public void printTicket() { this.printHeader(); super.printTicket(); } public void printHeader() { Header One }

33 A Footer Decorator class FooterDecorator1 extends TicketDecorator { public FooterDecorator1(Component c) { super(c); public void printTicket() { super.printTicket(); this.printFooter(); } public void printFooter() { System.out.println("% FOOTER one %"); }

34 A Client public class Client { public static void main(String[] args) { Component myST = Configuration.getSalesTicket(); myST.printTicket(); }

35 Simple Configuration // This method determines how to decorate SalesTicket class Configuration { public static Component getSalesTicket() { // Return a decorated SalesTicket return new HeaderDecorator1( new HeaderDecorator2( new FooterDecorator2( new FooterDecorator1( new SalesTicket() ) ; }

36 Output with Current Configuration Output: Header One >> Header Two << Customer: Bob The sales ticket itself Total: $ % FOOTER one % ## FOOTER two ##

37 The system on 2 slides SalesOrder delegates to Component to print ticket

38

39 Observe Customer  New Requirements: Send an to a new customer and verify the customer's address with the post office  If this was it, hard code Customer behavior when being added to data base

40 Or Use Observer  With additional behaviors (such as send advertisements via snail mail), there may be a changing list of objects that need notification that a new customer is being added  These objects will have different interfaces  Send , SendCouponsViaSnailMail, SellPrivateInformationToTelemarketers,....  Next up: change two objects into "Observers"

41 Observer  Have Customer extend Observable  Have all of the objects that need notification implement Observer (all have the update method)  Have some configurer add the correct observers to the Customer object with addObservers  Have the addCustomer method send the message notifyObservers

42 Design with Observer gatherCoupons()