Software Engineering Modern Approaches Eric Braude and Michael Bernstein 1.

Slides:



Advertisements
Similar presentations
Chapter 6 Introduction to Design Patterns. Sample Design Goals and Ways to Accomplish Them Reusability, Flexibility, and Efficiency o Reuse flexible designs.
Advertisements

Chapter 6 Introduction to Design Patterns (Part I) COSC 4346: Software Engineering I Dr. Lappoon R. Tang.
OOP Design Patterns Chapters Design Patterns The main idea behind design patterns is to extract the high level interactions between objects and.
Chapter 8 Structural Design Patterns o Facade o Decorator o Composite o Adapter o Flyweight o Proxy.
SWE 316: Software Design and Architecture – Dr. Khalid Aljasser Objectives Lecture 14 Structural Design Patterns SWE 316: Software Design and Architecture.
Computer Monitoring System for EE Faculty By Yaroslav Ross And Denis Zakrevsky Supervisor: Viktor Kulikov.
Iterators T.J. Niglio Computer & Systems Engineering Fall 2003 Software Design & Documentation Object Behavioral.
IEG3080 Tutorial 7 Prepared by Ryan.
Design Patterns CS is not simply about programming
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
Design Patterns academy.zariba.com 1. Lecture Content 1.What are Design Patterns? 2.Creational 3.Structural 4.Behavioral 5.Architectural 6.Design Patterns.
Operating Systems Concepts 1. A Computer Model An operating system has to deal with the fact that a computer is made up of a CPU, random access memory.
More OOP Design Patterns
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
Chapter 3.1:Operating Systems Concepts 1. A Computer Model An operating system has to deal with the fact that a computer is made up of a CPU, random access.
A First Program Using C#
Design Patterns Standardized Recurring model Fits in many location Opposite of customization Fundamental types of pattern Choose and use as desired and.
Design Patterns.
Chapter 10 Introduction to Components. Process Phases Discussed in This Chapter Requirements Analysis Design Implementation ArchitectureFramework Detailed.
Chapter 2 Object Orientation. Process Phase Affected by This Chapter Requirements Analysis Design Implementation ArchitectureFrameworkDetailed Design.
An Object-Oriented Approach to Programming Logic and Design
Chapter 5 Design Principles II: Flexibility, Reusability, and Efficiency.
Lecture # 06 Design Principles II
Chapter 5 Design Principles II: Flexibility, Reusability, and Efficiency.
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.
Chapter 8: Writing Graphical User Interfaces
05 - Patterns Intro.CSC4071 Design Patterns Designing good and reusable OO software is hard. –Mix of specific + general –Impossible to get it right the.
SOFTWARE DESIGN AND ARCHITECTURE LECTURE 09. Review Introduction to architectural styles Distributed architectures – Client Server Architecture – Multi-tier.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
SOEN 6011 Software Engineering Processes Section SS Fall 2007 Dr Greg Butler
Chapter 9 Behavioral Design Patterns o Interpreter o Iterator o Mediator o Observer o State o Chain of Responsibility o Command o Template.
Software Design Patterns
Patterns in programming 1. What are patterns? “A design pattern is a general, reusable solution to a commonly occurring problem in software. A design.
SWE 316: Software Design and Architecture Objectives Lecture # 15 Behavioral Design Patterns SWE 316: Software Design and Architecture  To learn the behavioral.
Design Patterns CSCI 5801: Software Engineering. Design Patterns.
18 April 2005CSci 210 Spring Design Patterns 1 CSci 210.
Software Design Patterns (1) Introduction. patterns do … & do not … Patterns do... provide common vocabulary provide “shorthand” for effectively communicating.
Computing IV Singleton Pattern Xinwen Fu.
Object Oriented Software Engineering Chapter 16 and 17 review 2014/06/03.
PowerPoint Presentation for Dennis & Haley Wixom, Systems Analysis and Design, 2 nd Edition Copyright 2003 © John Wiley & Sons, Inc. All rights reserved.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
Structural Design Patterns
ECE450S – Software Engineering II
Chapter 6 Introduction to Design Patterns. Process Phase Discussed in This Chapter Requirements Analysis Design Implementation ArchitectureFrameworkDetailed.
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.
SWE 316: Software Design and Architecture – Dr. Khalid Aljasser Objectives Lecture 13 Creational Design Pattern SWE 316: Software Design and Architecture.
CSC 480 Software Engineering Design With Patterns.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
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.
Final Review. From ArrayLists to Arrays The ArrayList : used to organize a list of objects –It is a class in the Java API –the ArrayList class uses an.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Design Patterns Introduction
1 Chapter 5:Design Patterns. 2 What are design pattern?  Schematic description of design solution to recurring problems in software design and,  Reusable.
© 2010 John Wiley & Sons Ltd. Software Engineering Modern Approaches Eric Braude and Michael Bernstein 1.
Interface Patterns. Adapter Provides the interface a client expects, using the services of a class with a different interface Note Avoid using object.
CS 5150 Software Engineering Lecture 16 Program Design 3.
Chapter 7 Creational Design Pattern. Process Phases Discussed in This Chapter Requirements Analysis Design Implementation ArchitectureFrameworkDetailed.
CSE 332: Design Patterns (Part II) Last Time: Part I, Familiar Design Patterns We’ve looked at patterns related to course material –Singleton: share a.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
Roberta Roth, Alan Dennis, and Barbara Haley Wixom
Object-Oriented Analysis and Design
Chapter 10 Design Patterns.
Chapter 5:Design Patterns
Introduction to Design Patterns
Behavioral Design Patterns
Design Patterns with C# (and Food!)
Frameworks And Patterns
Chapter 9 Behavioral Design Patterns
Presentation transcript:

Software Engineering Modern Approaches Eric Braude and Michael Bernstein 1

© 2010 John Wiley & Sons Ltd. Chapter 19 Software Design Patterns 2

Learning Goals for This Chapter What are examples of a recurring design purposes? What are “creational” design patterns? What are “structural” ones? What are “behavioral” design patterns? Can design patterns be thought of in terms of roles and basic forms? Requirements analysis Design Implementation Testing Maintenance Planning The Software Development Lifecycle Phase most relevant to this chapter is shown in bold 3

© 2010 John Wiley & Sons Ltd. KitchenViewer Interface Wall cabinet Counter Floor cabinet  ModernClassicAntiqueArts & Crafts menu display area styles 4

© 2010 John Wiley & Sons Ltd. KitchenViewer Example ModernClassicAntiqueArts & Crafts Wall cabinets Floor cabinets Countertop 5

© 2010 John Wiley & Sons Ltd. Selecting Antique Style ModernClassicAntiqueArts & Crafts 6

© 2010 John Wiley & Sons Ltd. KitchenViewer Without Design Patterns Kitchen Client renderKitchen() FloorCabinet ModernWallCabinet ModernFloorCabinetAntiqueFloorCabinet AntiqueWallCabinet WallCabinet 7

© 2010 John Wiley & Sons Ltd. AntiqueKStyle getWallCabinet() getFloorCabinet() The Abstract Factory Idea KitchenStyle getWallCabinet() getFloorCabinet() ModernKStyle getWallCabinet() getFloorCabinet() WallCabinetFloorCabinet AntiqueWallCabinetAntiqueFloorCabinet FloorCabinet getFloorCabinet() { return new AntiqueFloorCabinet(); } …… FloorCabinet getFloorCabinet() { return new ModernFloorCabinet(); } 8

© 2010 John Wiley & Sons Ltd. Abstract Factory Design Pattern Applied to KitchenViewer KitchenStyle getWallCabinet() getFloorCabinet() Kitchen getWallCabinet() getFloorcabinet() Client renderKitchen( KitchenStyle ) ModernKStyle getWallCabinet() getFloorCabinet() AntiqueKStyle getWallCabinet() getFloorCabinet() WallCabinetFloorCabinet ModernWallCabinet ModernFloorCabinet AntiqueWallCabinet AntiqueFloorCabinet 9

© 2010 John Wiley & Sons Ltd. Abstract Factory Design Pattern Style getComponentA() getComponentB() Client doOperation( Style myStyle ) Style1 getComponentA() getComponentB() Style2 getComponentA() getComponentB() ComponentAComponentB Style1ComponentA Style1ComponentB Style2ComponentA Style2ComponentB Collection 10

© 2010 John Wiley & Sons Ltd. Abstract Factory Design Pattern Alternative Style getComponentA() getComponentB() Client doOperation() Style1 getComponentA() getComponentB() Style2 getComponentA() getComponentB() ComponentAComponentB Style1ComponentA Style1ComponentB Style2ComponentA Style2ComponentB Collection getComponentA() getComponentB() 11

Key Creational Patterns Design Pattern Name Approximate Design Purpose Satisfied by this Pattern Example Application Purpose Satisfied by this Pattern Outline of the Design Pattern Design for the following requirements without repeating code unnecessarily. Make the design easy to change. Factory Create objects at runtime with flexibility that constructors alone cannot provide. From a single version of control code, generate mail messages tailored to various customers. Create desired objects by using methods that return the objects. Abstract Factory Create coordinated families of objects at runtime, chosen from a set of styles. Display a kitchen layout, allowing the user to select a style at runtime. Encapsulate each family in a class whose methods return objects in that style. Prototype Create an aggregate object in which selected parts are essentially copies. Display a kitchen layout, allowing the user to select at runtime a type of wall cabinet, or a type of floor cabinet etc. Create the objects of the type by cloning a prototype. Singleton Ensure that a class has at most one instantiation, accessible throughout the application. Build an application to evaluate the results of a lab experiment. Ensure that there is exactly one Experiment object at runtime, and ensure that it can be accessed by any method in the application. Make the constructor private and obtain the unique object by means of a public method that returns it. © 2010 John Wiley & Sons Ltd. 12

Key Structural Patterns Design Pattern Name Approximate Design Purposes Satisfied by this Pattern Example of Design Purposes Satisfied by this Pattern: Summary of the Design Pattern Design for the following requirements without repeating code unnecessarily. Make the design easy to change. Composite Represent a tree of objects. Allow client code to access uniform functionality distributed in the subtree rooted by any node. Represent the organization chart of a company. Allow client code to call printOrganization() on any Employee object, printing the names of the employee and all subordinates, if any. Allow the addition and removal of subtrees at runtime. Have composite objects aggregate other composite objects. Decorator Allows objects and functionality to be added to an object at runtime. Allow the user of an online clothing store to see an image of himself dressed in a variety of clothes. Link the objects using aggregation. Adapter Allow an application to make use of external (e.g., legacy) functionality. Design a loan application from scratch, but allow it to use any vendor’s classes that compute monthly payment calculations. Introduce an inherited intermediary class relating the application and the class with desired functionality. 13

Design Pattern Name Approximate Design Purposes Satisfied by this Pattern Example of Design Purposes Satisfied by this Pattern: Summary of the Design Pattern Design for the following requirements without repeating code unnecessarily. Make the design easy to change. Façade Manage software architectures involving large numbers of classes. Design the architecture of a student loan software application so that one group of developers can concentrate on the loan option database, another on the user interface (simultaneously), and a third on payment calculations. Minimize coordination problems. For each package, introduce an object which is the sole access to objects within the package. Flyweight Obtain the benefits of having a large number of individual objects without excessive runtime space requirements. We want to be able to visualize a room with stenciling. There are five stencil patterns but thousands of potential stencil marks on the walls. This might be easy to do if each mark were a separate object, but we can’t afford the memory required, and it’s impractical to name all of these separate objects. Share objects by parameterizing the methods with variables expressing the context. Proxy Some methods are remote, or require lots of resources to execute (time or space). Ensure that they can be executed, but no more often than necessary. Assume that rendering an image consumes a significant amount of time and space because the image data has to be read from a file, fill a buffer, and then be rendered. If the buffer is already filled by a previous invocation of the method, then invoking the function should not repeat this step. Introduce a class standing between the requesting methods and the resource. 14

© 2010 John Wiley & Sons Ltd. Example of Behavioral Design Goal: Port Traffic berth obstacles to drydock  Algorithms express mutual behavior 15

© 2010 John Wiley & Sons Ltd. ShipTugboat 1..n1 Harbor Application Customs application: reuse Ship alone ShipLongshoreman  Avoiding Dependencies 16

Core Mediator Concept Applied to The Harbor Problem Ship Tugboat LeavingPort estimateTime() © 2010 John Wiley & Sons Ltd. 17

Applying the Mediator Design Pattern to The Harbor Problem ShipTugboat Vessel PortMission estimateTime() LeavingPort estimateTime() EnteringPort estimateTime() BeingMaintained estimateTime() Mediator base class © 2010 John Wiley & Sons Ltd. 18

Behavioral Design Patterns: Name Design Purposes Satisfied by this Pattern Example of Design Purposes Satisfied by this Pattern: Summary of the Design Pattern Design for the following requirements without repeating code unnecessarily. Make the design easy to change. Chain of Responsibility We want a collection of objects to exhibit functionality. At design time we want to be able to easily add or delete objects that handle all or part of the responsibility. Design a GUI for a web application to view automobiles with requested color etc. The display is dynamic, depending on the model etc. chosen. Reuse the GUI parts among the displays. Link objects to each other via aggregation. Each performs some of the work, and then calls on the next object in the chain to continue the work. Command Make the execution of operations more flexible. For example, enable “undoing.” Allow users of an application to retract their last four decisions at any time (the “undo” problem) Capture each command in a class of its own. Interpreter (see section ) Parse an expression. Design an application that takes as input an order for a network of PC’s, expressed in a standard syntax. The output consists of instructions for assembling the network. (see section ) Introduce a class to capture expressions, and allow expression classes to aggregate expression classes. Mediator (see above) Capture the interaction between objects without having them reference each other (thus permitting their reuse). Build an application that estimates the amount of time required to bring ships into and out of a harbor, and to transport them to dry dock for maintenance: But ensure that the Ship and Tugboat classes can be reused separately. Capture each interaction in a separate class, which aggregates the objects involved. 19

Approximate Design Pattern Name Design Purposes Satisfied by this Pattern Example of Design Purposes Satisfied by this Pattern: Summary of the Design Pattern Design for the following requirements without repeating code unnecessarily. Make the design easy to change. Observer A set of objects depends on the data in a single object. Design a way in which they can be updated when that single object changes attribute values. Keep management, marketing and operations departments up to date on sales data. Each of these departments has different requirements for the data. Capture the data source as a class. Allow it to loop through the observer objects, calling an update() method. State At runtime, vary the effect of invoking an object’s methods depends upon the object’s state. Customers fill out an order form on a web site, and then hit the “enter” button. The result must depend upon the state of the form data: “Product Information Complete,” “Personal Information Incomplete,” “Credit Check In Progress” etc. Aggregate a class representing the state with operative method doAction(): Subclasses effect the required actions of substates with their own versions of doAction(). Template Allow an algorithm to execute partial variants at runtime. Organize the huge number of traffic light algorithms in a city by arranging them into a few basic forms, with variants tailored to specific locations. Have a base class contain an overall method, but with function calls where variability is needed. Have subclasses implement these function calls to capture the required variability. 20

© 2010 John Wiley & Sons Ltd. Characteristics of Design Patterns 1  Viewpoints – ways to describe patterns 1.Static: class model (building blocks) 2.Dynamic: sequence or state diagram (operation)  Levels – decomposition of patterns 1.Abstract level describes the core of the pattern 2.Concrete (= non abstract) level describes the particulars of this case  Roles – the “players” in pattern usage 1.Application of the design pattern itself 2.Clients of the design pattern application 3.Setup code initializes and controls 21

Characteristics of Design Patterns 2 1. Client role 2. Setup role 3. Role: Application of the design pattern (class or classes) : Reference direction © 2010 John Wiley & Sons Ltd. 22

Characteristics of Design Patterns 2 1. Client role 2. Setup role A C A. Static viewpointB. Dynamic viewpoint 3. Role: Application of the design pattern D B (i) Abstract level (ii) Concrete level (class model) (sequence or state diagram) (class or classes) : Reference direction © 2010 John Wiley & Sons Ltd. 23

© 2010 John Wiley & Sons Ltd. Abstract Factory Application Sequence Diagram myStyle :KitchenStyle Client myStyle: ModernKStyle renderKitchen ( myStyle ) wallCabinet1: ModernWallCabinet ModernWallCabinet() getWallCabinet() myStyle. getWallCabinet() -- IF myStyle BELONGS TO ModernKStyle -- 24

© 2010 John Wiley & Sons Ltd. getWallCabinet() Abstract Factory Application Sequence Diagram myStyle :KitchenStyle Client myStyle: ModernKStyle myStyle: AntiqueKStyle renderKitchen ( myStyle ) wallCabinet1: ModernWallCabinet wallCabinet1: AntiqueWallCabinet ModernWallCabinet() getWallCabinet() AntiqueWallCabinet() myStyle. getWallCabinet() -- IF myStyle BELONGS TO ModernKStyle IF myStyle BELONGS TO AntiqueKStyle -- 25

© 2010 John Wiley & Sons Ltd. Concrete and Abstract Layers Client Abstract level Concrete level 26

© 2010 John Wiley & Sons Ltd. Concrete and Abstract Layers KitchenStyle Kitchen Client ModernKStyle AntiqueKStyle WallCabinet FloorCabinet ModernWallCabinet ModernFloorCabinet AntiqueWallCabinet AntiqueFloorCabinet Abstract level Concrete level 27

© 2010 John Wiley & Sons Ltd. 2. Client Role1. Design Pattern Application 3. Setup Role The Three Roles Involved in Design Pattern Usage Rest of the Application 28

© 2010 John Wiley & Sons Ltd. 2. Client Role1. Design Pattern Application Interface to the pattern (frequently abstract; possibly several classes) DPClient DPInterface Rest of the design pattern application Interacts with the design pattern only through its interface 3. Setup Role The Three Roles Involved in Design Pattern Usage Rest of the Application No limitations 29

© 2010 John Wiley & Sons Ltd. Design Purpose S Ensure that there is exactly one instance of a class S. Be able to obtain the instace from anywhere in the application. Singleton 30

© 2010 John Wiley & Sons Ltd. Design Purpose S Ensure that there is exactly one instance of a class S. Be able to obtain the instace from anywhere in the application. Design Pattern Summary S SS; Make the constructor of S private; define a private static attribute for S of type S; define a public accessor for it. Singleton 31

© 2010 John Wiley & Sons Ltd. Singleton : Class Model Singleton Design Pattern MyClass getSingletonOfMyClass(): MyClass Client 1 singletonOfMyClass «static» 32

© 2010 John Wiley & Sons Ltd. The Singleton Design Pattern -- applied to MyClass 1.Define a private static member variable of MyClass of type MyClass private static MyClass singletonOfMyClass = new MyClass(); 2.Make the constructor of MyClass private private MyClass() { /* …. constructor code …. */ }; 3.Define a public static method to access the member public static MyClass getSingletonOfMyClass() { return singletonOfMyClass; } 33

Output for Singleton Experiment Example © 2010 John Wiley & Sons Ltd. 34

© 2010 John Wiley & Sons Ltd. Application of Singleton to Experiment Example Experiment theExperiment: Experiment analyze() getTheExperiment(): Experiment reportResults() Client theExperiment 1 «static» 35

Word Processor Interaction 1 of 2 ---> Enter title : My Life ---> Enter Heading or “-done”: Birth ---> Enter text: I was born in a small mountain hut …. ---> Enter Heading or “-done”: Youth ---> Enter text: I grew up playing in the woods … ---> Enter Heading or “-done”: Adulthood …. ---> Enter Heading or “-done”: -done ( continued ) © 2010 John Wiley & Sons Ltd. 36

Word Processor Interaction 2 of 2 : Output Options …. >> Enter the style you want displayed: big Title: MY LIFE Section BIRTH --- I was born in a mountain hut …. Section YOUTH --- I grew up sturdy … Section ADULTHOOD --- …. >> Enter the style you want displayed: small My Life Birth I was born in a mountain hut …. Youth I grew up sturdy … Adulthood Option 2Option 1 © 2010 John Wiley & Sons Ltd. 37

Design Purpose “Provide an interface for creating families of related or dependent objects without specifying their concrete classes.”* Abstract Factory * Gamma et al © 2010 John Wiley & Sons Ltd. 38

Design Purpose “Provide an interface for creating families of related or dependent objects without specifying their concrete classes.”* Design Pattern Capture family creation in a class containting a factory method for each class in the family. Abstract Factory * Gamma et al © 2010 John Wiley & Sons Ltd. 39

© 2010 John Wiley & Sons Ltd. Abstract Factory * Abstract Factory Interface Style…. Client StyleAFactoryStyleBFactory Ensemble setAbstractFactory() doAFunction() AbstractFactory getAPart1Object() getAPart2Object() * relationships within pattern application not shown 40

© 2010 John Wiley & Sons Ltd. Application of Abstract Factory Interface of Abstract Factory Applied to Word Processor Client SmallStyleLargeStyle Style Document setStyle() display()

© 2010 John Wiley & Sons Ltd. «create» The Abstract Factory Idea Ensemble setAbstractFactory() doAFunction() AbstractFactory getAPart1Object() getAPart2Object() StyleAFactory getAPart1Object() getAPart2Object() Part1Part2 Part1StyleAPart2StyleA abstractFactory1 Client 42

© 2010 John Wiley & Sons Ltd. «create» Abstract Factory Style…. AbstractFactory getAPart1Object() getAPart2Object() StyleAFactoryStyleBFactory Part1Part2 Part1StyleAPart1StyleBPart2StyleAPart2StyleB abstractFactory1 Ensemble doAFunction() Client 1..n Part… 43

} } Sequence Diagram for Abstract Factory StyleXFactory() :ClientabstractFactory :StyleXFactory :Ensemble setAbstractFactory (abstractFactory ) getAPart_i() Part_iStyleX() Selecting a style Creating a Part_i object in required style getAPart_i() abstractFactory :AbstractFactory :Part_iStyleX doAFunction() Virtual function property Assume that this method requires a Part_i object. © 2010 John Wiley & Sons Ltd. 44

© 2010 John Wiley & Sons Ltd. Abstract Factory Applied to Word Processor Document getAHeading() getATitle() grtDocumentFromUser() «create» SmallStyle getAHeading() getATitle() LargeStyle getAHeading() getATitle() Title value Heading value LargeHeading display() SmallHeading display() LargeTitle display() SmallTitle display() Text value 1 0..n Style getAHeading() getATitle() Displayable display() Client getStyleFromUser() displayDocument() style 45

“Word Processor” Interaction © 2010 John Wiley & Sons Ltd. 46

© 2010 John Wiley & Sons Ltd. Design Purpose Provide an interface to a package of classes Design Pattern Summary Define a singleton which is the sole means for obtaining functionality from the package. Facade Notes : the classes need not be organized as a package; more than one class may be used for the façade. 47

© 2010 John Wiley & Sons Ltd. Facade Design Pattern Structure C «not exposed» myCMethod() Façade «exposed» cMethodOfFacade() Client

© 2010 John Wiley & Sons Ltd. Facade Design Pattern Structure «not exposed» C «not exposed» myCMethod() Façade «exposed» cMethodOfFacade() Client 1 2 «not exposed» This call replaced by 1 & 2. Client can’t reference C 49

© 2010 John Wiley & Sons Ltd. Sequence Diagram for Façade :Client cMethodOfFacade() singleton :Facade :C myCMethod() (return if any) 50

Using Façade for Architecture of a Video Game MyGameCharacters MyGameEngine MyGameCast «facade» MyGame «facade» MyGameEnvironment «facade» © 2010 John Wiley & Sons Ltd. 51

© 2010 John Wiley & Sons Ltd. Design Purpose Allow an application to use external functionality in a retargetable manner. Adapter 52

© 2010 John Wiley & Sons Ltd. Design Purpose Allow an application to use external functionality in a retargetable manner. Design Pattern Summary Write the application against an abstract version of the external class; introduce a subclass that aggregates the external class. Adapter 53

© 2010 John Wiley & Sons Ltd. Adapter Example Client AbstractClass clientNameForRequiredMethod() Adapter clientNameForRequiredMethod() { adaptee. requiredMethod();} adaptee RequiredClass requiredMethod() 54

© 2010 John Wiley & Sons Ltd. Sequence Diagram for Adapter :Client clientNameForRequiredMethod() :AbstractClass :Adapter RequiredMethod() adaptee :RequiredClass 55

Adapter Design Pattern Financial amount() Principle computeValue() Client Legacy systemAdaptationApplication © 2010 John Wiley & Sons Ltd. 56

Adaptation FinancialAdapter amount() Adapter Design Pattern { legacyAdaptee.computeValue(); } Financial amount() Principle computeValue() Client Legacy system legacyAdaptee Application © 2010 John Wiley & Sons Ltd. 57

Adaptation MyListener actionPerformed() Java Listeners as Adapters Result of button press MyButton addActionListener() ActionListener MyClass myMethod() actionListener © 2010 John Wiley & Sons Ltd. 58

© 2010 John Wiley & Sons Ltd. Adapter Example: Inheritance Version Client AbstractClass standinForRequiredMethod() Adapter standinForRequiredMethod() { requiredMethod();} RequiredClass requiredMethod() 59

© 2010 John Wiley & Sons Ltd. Design Purpose Interpret expressions written in a formal grammar. Interpreter 60

© 2010 John Wiley & Sons Ltd. Design Purpose Interpret expressions written in a formal grammar. Design Pattern Summary Represent the grammar using a Recursive design pattern form: Pass interpretation to aggregated objects. Interpreter 61

Interpreter Client Interface AbstractExpression interpret() Client © 2010 John Wiley & Sons Ltd. 62

Interpreter Design Pattern AbstractExpression interpret() Client TerminalExpression interpret() NonTerminalExpression interpret() 1..n © 2010 John Wiley & Sons Ltd. 63

© 2010 John Wiley & Sons Ltd. interpret() Interpreter Sequence Diagram TerminalExpression :NonterminalExpression :Client AbstractExpression NonterminalExpression... create & interpret() create & interpret()... 64

Example of a Virtual Machine “Program” 700Mhz & 512MB 800Mhz & 768MB 500Mhz & 512MB assemble …. Graphics reproduced with permission from Corel. © 2010 John Wiley & Sons Ltd. 65

Input For Network Assembly Example © 2010 John Wiley & Sons Ltd. 66

Output of Network Assembly Example (1 of 3) © 2010 John Wiley & Sons Ltd. 67

Output of Network Assembly Example (2 of 3) © 2010 John Wiley & Sons Ltd. 68

Output of Network Assembly Example (3 of 3) © 2010 John Wiley & Sons Ltd. 69

Interpreter Design Pattern Component assemble() NetSystem assemble() component1 Client © 2010 John Wiley & Sons Ltd. 70

Application of Interpreter Design Pattern Component assemble() Computer assemble() NetSystem assemble() component1 component2 RAM describe() CPU describe() cpu ram Client Setup getInputFromUser() parse() © 2010 John Wiley & Sons Ltd. 71

© 2010 John Wiley & Sons Ltd. Design Purpose Arrange for a set of objects to be affected by a single object. Observer 72

© 2010 John Wiley & Sons Ltd. Design Purpose Arrange for a set of objects to be affected by a single object. Design Pattern Summary The single object aggregates the set, calling a method with a fixed name on each member. Observer 73

© 2010 John Wiley & Sons Ltd. Observer Design Pattern Source notify() Observer update() for all Observer’s o: o.update(); Client of this system n Server partClient part 74

© 2010 John Wiley & Sons Ltd. Observer Design Pattern Source notify() Observer update() ConcreteSource state ConcreteObserver observerState update() for all Observer’s o: o.update(); Client n Server partClient part 1 75

© 2010 John Wiley & Sons Ltd. Observer Applied to International Hamburger Co. Source notify() Observer update() Headquarters demand SeniorManagement forecast update() Client 1..n Marketing marketingDemand update() doDisplay() if( abs( hq.demand - marketingDemand ) > 0.01 ) {marketingDemand = hq.getDemand(); doDisplay(); } Server partClient part 76

I/O Example for Mutual Fund Observer Example Note: HiGrowthMutualFund starts with 3 shares of Awesome, assumes price of 1.0, and has non-Awesome holdings totalling Note: MedGrowthMutualFund starts with 2 shares of Awesome, assumes price of 1.0, and has non-Awesome holdings totalling Note: LoGrowthMutualFund starts with 1 shares of Awesome, assumes price of 1.0, and has non-Awesome holdings totalling Enter 'quit': Any other input to continue. go on Enter the current price of Awesome Inc. in decimal form Value of Lo Growth Mutual Fund changed from to Value of Med Growth Mutual Fund changed from to Value of Hi Growth Mutual Fund changed from to Enter 'quit': Any other input to continue. go on Enter the current price of Awesome Inc. in decimal form Value of Lo Growth Mutual Fund changed from to Value of Med Growth Mutual Fund changed from to Value of Hi Growth Mutual Fund changed from to Enter 'quit': Any other input to continue. © 2010 John Wiley & Sons Ltd. 77

© 2010 John Wiley & Sons Ltd. Observable notifyObservers() Observer update( Observable, Object ) AwesomeInc price LongTermMutualFund …. update(…) Observer Example: Mutual Funds Key: Developer Class Java API Class MediumTermMutualFund …. update(…) HiGrowthMutualFund …. update(…) MutualFund value numAwesomeShares Client Setup 78

© 2010 John Wiley & Sons Ltd. Observable notifyObservers() Observer update( Observable, Object ) MyObservable MyConcreteObserver observerState update(…) Observer in the Java API subject Key: Developer Class Java API Class 79

© 2010 John Wiley & Sons Ltd. Design Purpose Cause an object to behave in a manner determined by its state. State 80

© 2010 John Wiley & Sons Ltd. Design Purpose Cause an object to behave in a manner determined by its state. Design Pattern Summary Aggregate a State object and delegate behavior to it. State 81

© 2010 John Wiley & Sons Ltd. Target doRequest() State Design Pattern Basic Structure: doRequest() behaves according to state of Target targetState TargetState handleRequest() Client 1 { targetState.handleRequest(); } 82

© 2010 John Wiley & Sons Ltd. Target doRequest() State Design Pattern Class Model targetState TargetState handleRequest() Client 1 TargetState1 handleRequest() TargetState1 handleRequest() TargetState1 handleRequest() 83

© 2010 John Wiley & Sons Ltd. TargetStateB handleRequest() Target doRequest() State Design Pattern Structure: doRequest() behaves according to state of Target targetState TargetState handleRequest() Client TargetStateA handleRequest() 1 { targetState.handleRequest(); }... 84

GUI For a Role-Playing Video Game Set Characteristics Courtesy Tom VanCourt and Corel 85

State Design Pattern Applied to Role-Playing Game MyGame setCharacteristics() MyGameState handleClick() state { state.handleClick(); } Engaging handleClick() SettingUp handleClick() Waiting handleClick() SettingCharacteristics handleClick() { showWindow(); …. // more } { showWindow(); …. // more } { // already responding … // display message } { // do nothing … // display message } © 2010 John Wiley & Sons Ltd. 86

© 2010 John Wiley & Sons Ltd. Basic Idea of Delegation requiredFunction() … intermediaryFunction( … ) { … requiredFunction() … } Client clientFunction() intermediaryFunction() replace  … clientFunction( … ) { … intermediaryFunction( … ) … } 87

© 2010 John Wiley & Sons Ltd. Basic Design Pattern Form #1: Delegation DoerBase doIt() DPInterface interfaceMethod() ConcreteDoer1 doIt() ConcreteDoer2 doIt()... doerObject … interfaceMethod( … ) { … doerObject.doIt() … } Client 88

© 2010 John Wiley & Sons Ltd. Basic Design Pattern Form #2: Recursion RecursionBase doOperation() NonrecursiveClass doOperation() RecursiveClass doOperation() void doOperation( … ) { … aggregate … } aggregate Client 89

© 2010 John Wiley & Sons Ltd. The Recursion Form Applied to an Organization Chart Employee printOrganization() IndividualContributor printOrganization() Supervisor printOrganization() void printOrganization( … ) { … supervisees.printOrganization() … } supervisees Client 90

© 2010 John Wiley & Sons Ltd. Summary of This Chapter  Design Patterns are recurring designs satisfying recurring design purposes  Described by Static and Dynamic Viewpoints – Typically class models and sequence diagrams respectively  Use of a pattern application is a Client Role – Client interface carefully controlled – “Setup,” typically initialization, a separate role  Design patterns Forms usually Delegation or Recursion  Classified as Creational, Structural, or Behavioral 91