part 4 elaboration iteration 2 – more patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 chapter...

64
1 PART 4 PART 4 Elaboration Elaboration Iteration 2 Iteration 2 More More Patterns Patterns Chapter 22 Chapter 22 UML Tools and UML Tools and UML as Blueprint UML as Blueprint

Upload: others

Post on 16-Apr-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

1

PART 4 PART 4 Elaboration Elaboration

Iteration 2 Iteration 2 –– More More Patterns Patterns

Chapter 22Chapter 22UML Tools and UML Tools and

UML as Blueprint UML as Blueprint

Page 2: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

2

3

Forward, Reverse, Forward, Reverse, and Roundand Round--Trip Engineering Trip Engineering

• Forward engineering– The generation of code from diagrams;

• Reverse engineering– Generation of diagrams from code

• Round-trip engineering– Generation in either direction and can synchronize between

UML diagrams and code, ideally automatically and immediately as either is changed.

• All UML tools claim to support these features, but many are half crippled.– Many tools can only do the static models– If tool can generate a sequence diagram from the code, you

can then much more easily follow the call-flow logic of the system to learn its basic collaborations.

code

code

4

Common Report of Valuable Common Report of Valuable Features Features

• The most consistent report of UML tool value– Claim the value for reverse engineering

• As a visualization learning aid to understand existing code.• Generating UML package, class, and interaction diagrams

from code and viewing the diagrams on a monitor, or printing them on large plotter paper

• As more UML tools become well-integrated with text-strong IDEs (Eclipse, Visual Studio..), and their usability improves– More consistent value will be reported in using the

tools for both forward and round-trip engineering.

Page 3: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

3

5

What to Look For in a Tool ?What to Look For in a Tool ?• Comments on choosing a UML tool

– First, try a free UML tool. – Once you’ve chosen a tentative tool, try it on a real

project with as many developers as possible, before making a decision.

• Decide based on the guidance of your developers who have really used it for a long period, not based on the opinion of architects or others who have only made a cursory investigation

– Choose a UML tool that integrates into your favorite text-strong IDE.

– Choose a UML tool that supports reverse engineering sequence diagrams from code.

– Choose a tool that supports printouts to a plotter, on large plotter paper, in large font and diagram sizes, so that large-scale visualization is possible.

6

Update the Diagrams After Update the Diagrams After Coding Coding

• If using a UML tool integrated with an IDE, working alone, and not doing wall sketching– Synchronizing the diagrams is a simple reverse-engineering

operation in the IDE.

• If applying UML as sketch– Scenario

• At the start of a three-week time boxed iteration, there was a modeling day involving UML wall sketches.

• This is followed by about three weeks of code and test.• Finally, it's time to start the next iteration's modeling day.

– How to proceed?• Use a UML tool to reverse engineer the code into UML diagrams,

package, class, and interaction diagrams. • Print the most interesting ones large on long plotter paper.• Sketch on top of them, and sketch below them on whiteboards or

static cling sheets.

Page 4: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

4

Chapter 23Chapter 23Quick Analysis Quick Analysis

Update Update

8

Case Study: NextGen POS Case Study: NextGen POS 11

• Objectives– Quickly highlight some analysis artifact changes.

• NextGen POS– Use Cases

• No refinement is needed for the use cases this iteration.• In UP, 1~2 day requirements workshop near the end of iteration-1 and

the end of iteration-2 to investigate more requirements in detail.• The previously analyzed use cases (e.g. Process Sale) will be revisited

and refined based on insights gained from iteration-1 programming and tests.

• In iterative methods, early programming and testing with parallel requirements analysis improved by feedback from early development.

– SSDs• This iteration includes adding support for third-party external systems

with varying interfaces, such as a tax calculator. • SSDs should be updated to reflect some of the inter-system

collaborations.

Page 5: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

5

9

Case Study: NextGen POS Case Study: NextGen POS 22

• An SSD scenario that illustrates some external systems

10

Case Study: NextGen POS Case Study: NextGen POS 33

– Domain Model• In contrast to the prior iteration, the requirements being

tackled this time do not involve many new domain concepts.– A brief survey of the new requirements suggests PriceRule as a

domain concept

• In this situation, we can skip refining the Domain Model, and move quickly to design work, and let the discovery of new domain concepts occur during object design in the Design Model, when the developers are thinking through a solution, or indeed even while coding.

• There can be not only too much modeling, but too little.– Developers often avoid any analysis or modeling because it seems

like a low-value and time-consuming affair.• Modeling can add value

– If one masters the basic guidelines of analysis and design, becomes comfortable with the "languages" and applies these in the spirit of agile modeling.

Page 6: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

6

11

Case Study: NextGen POS Case Study: NextGen POS 33

– System Operation Contracts• No new system operations are being considered in this

iteration.• In any event, contracts are only an option to consider when

the detailed precision they offer is an improvement over the descriptions in the use cases.

Chapter 24Chapter 24Iteration 2 Iteration 2

More Patterns More Patterns

Page 7: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

7

13

From Iteration 1 to 2 From Iteration 1 to 2 • Objective

– Define requirements for iterations-2.

• When iteration-1 ends, the following should be accomplished:– All the software has been tested: unit, acceptance, load,

usability, and so on. – The idea in the UP is to do early, realistic, and continuous

verification of quality and correctness, so that early feedback guides the developers to adapt and improve the system.

– Customers have been regularly engaged in evaluating the partial system, to obtain feedback for adaptation and clarification of requirements.

– The system, across all subsystems, has been completely integrated and stabilized as a baselined internal release.

14

From Iteration 1 to 2 From Iteration 1 to 2 • Some skipped activities

– An iteration planning meeting to decide what to work on in the next iteration, resolve questions, and identify major tasks.

– The start of the new iteration, use a UML tool to reverse engineer diagrams from the source code of the last iteration (the results are part of Design Model).

• To illustrate the starting point of the logical design for the next iteration.

– Usability analysis and engineering for the UI is underway.– Database modeling and implementation is underway.– Another two-day (for example) requirements workshop occurs, and

more use cases are written in their fully dressed format. • During elaboration, while perhaps 10% of the most risky

requirements are being designed and implemented, there is a parallel activity to deeply explore and define perhaps 80% of the use cases for the system.

• Participants include developers/architect from the first iteration, so that the investigation and questioning during this workshop is informed from the insights gained from actually quickly building some software.

Page 8: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

8

15

IterationIteration--2 Requirements and Emphasis: 2 Requirements and Emphasis: Object Design and Patterns Object Design and Patterns 11

• For case studies– Iteration-2 ignores requirements analysis and domain analysis,

and focuses on object design with responsibilities and GRASP, and applying some GoF design patterns.

• Iteration-2 of the NextGen POS application handles several interesting requirements:– Support for variations in third-party external services. For

example, different tax calculators must be connectable to the system, and each has a unique interface.

– Complex pricing rules.– A design to refresh a GUI window when the sale total

changes.– Note: the above requirements are not newly discovered; these

interesting requirements may be identified during inception. (e.g., the Process Sale use case indicates the pricing problem)

16

IterationIteration--2 Requirements and Emphasis: 2 Requirements and Emphasis: Object Design and Patterns Object Design and Patterns 22

• The original Process Sale use case indicates the pricing problem: – Main Success Scenario of Process Sale use case :

• 1.Customer arrives at a POS checkout with goods and/or services to purchase.

• 2.Cashier tells System to create a new sale.• 3.Cashier enters item identifier.• 4.System records sale line item and presents item description,

price, and running total. Price calculated from a set of price rules.

• ...– Supplementary Specification record details of the domain rules

for pricing, and indicate the need to support varying external systems.

Page 9: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

9

17

IterationIteration--2 Requirements and Emphasis: 2 Requirements and Emphasis: Object Design and Patterns Object Design and Patterns 33

• Supplementary Specification– ...– Interfaces– Software Interfaces– For most external collaborating systems (tax calculator, accounting,

inventory, ... ) we need to be able to plug in varying systems and thus varying interfaces.

– ...– Domain (Business) Rules

............

Senior15% off.

Preferred Customer10% off.

Each retailer uses different rules.

Employee20% off.

Retailer policy.High.Purchaser discount rules. RULE4

SourceChangeabilityRuleID

18

IterationIteration--2 Requirements and Emphasis: 2 Requirements and Emphasis: Object Design and Patterns Object Design and Patterns 44

• Supplementary Specification (cont’d)– Information in Domains of Interest– Pricing

• In addition to the pricing rules described in the domain rules section, note that products have an original price, and optionally a permanent markdown price. A product's price (before further discounts) is the permanent markdown price, if present. Organizations maintain the original price even if there is a permanent markdown price, for accounting and tax reasons.

– ...

Page 10: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

10

19

IterationIteration--2 Requirements and Emphasis: 2 Requirements and Emphasis: Object Design and Patterns Object Design and Patterns 55

• Incremental Development for a Use Case Across Iterations– Because of these requirements, we are revisiting the Process Sale

use case in iteration-2, but implementing more scenarios.– It is common to work on varying scenarios or features of the same

use case over several iterations and gradually extend the system to ultimately handle all the functionality required.

– Short, simple use cases may be completely implemented within one iteration.

– One scenario should not be split across iterations; an iteration should complete one or more end-to-end scenarios.

– Iteration-1 made simplifications so that the problem and solution were not overly complex to explore.

Chapter 25Chapter 25GRASP: More GRASP: More Objects with Objects with

Responsibilities Responsibilities

Page 11: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

11

21

ObjectiveObjective• Objective

– Learn to apply the remaining GRASP patterns

• GRASP patterns already covered– Information Expert, Creator, High Cohesion, Low

Coupling, Controller

• GRASP patterns covered in this chapter– Polymorphism– Indirection– Pure Fabrication– Protected Variations

22

Polymorphism Polymorphism 11

• Problem– How to handle alternatives based on type? How to

create pluggable software components?– Alternatives based on type

• Conditional variation is a fundamental theme in programs. • If a program is designed using if-then-else or case

statement conditional logic, then if a new variation arises, it requires modification of the case logic — often in many places.

– Pluggable software components• Viewing components in client-server relationships, how can

you replace one server component with another, without affecting the client?

Page 12: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

12

23

Polymorphism Polymorphism 22

• Solution– When related alternatives or behaviors vary by type (class),

assign responsibility for the behavior — using polymorphic operations — to the types for which the behavior varies

• Example 1– NextGen POS

• Multiple external third-party tax calculators must be supported(such as Tax-Master and Good-As-Gold TaxPro)

• Each tax calculator has a different interface, so there is similar but varying behavior to adapt to each of these external fixed interfaces or APIs

• The behavior of calculator adaptation varies by the type of calculator, by Polymorphism we should assign the responsibility for adaptation to different calculator (or calculator adapter) objects themselves, implemented with a polymorphic getTaxes operation

24

Polymorphism Polymorphism 33

Page 13: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

13

25

Polymorphism Polymorphism 44

• Example 2– Monopoly Problem: How to Design for Different Square Actions?

• When a player lands on the Go square, they receive $200. There's a different action for landing on the Income Tax square, and so forth. Notice that there is a different rule for different types of squares

• It varies for the types (classes) RegularSquare, GoSquare, and so on.

• What is the operation that varies? It's what happens when a player lands on a square.

• By Polymorphism, we'll create a separate class for each kind of square that has a different landedOn responsibility, and implement a landedOn method in each

26

Polymorphism Polymorphism 55

Abstract

Page 14: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

14

27

Polymorphism Polymorphism 66

• Guideline: Unless there is a default behavior in the superclass, declare a polymorphic operation in the superclass to be {abstract}

• The remaining interesting problem is the dynamic design: – How should the interaction diagrams evolve? – What object should send the landedOn message to the square

that a player lands on? – Since a Player software object already knows its location

square (the one it landed on), then by the principles of Low Coupling and by Expert, class Player is a good choice to send the message, as a Player already has visibility to the correct square

28

Polymorphism Polymorphism 77

visibility

Page 15: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

15

29

Polymorphism Polymorphism 88

• Consider each of the polymorphic cases in terms of GRASP and the design issues: – GoSquare

• By low representational gap, the Player should know its cash. Therefore, by Expert, the Player should be sent an addCashmessage. Thus the square needs visibility to the Player so it can send the message

– RegularSquare• In this case, nothing happens• In code, the body of this method will be empty — sometimes

called a NO-OP (no operation) method. Note that to make the magic of polymorphism work, we need to use this approach to avoid special case logic

– IncomeTaxSquare• By low representational gap and by Expert, who should know this?

The Player. Thus the square asks for the player's worth, and then deducts the appropriate amount

– GoToJailSquare• Simply, the Player's location must be changed. By Expert, the

Player should receive a setLocation message

30

Polymorphism Polymorphism 99

The RegularSquare case

The IncomeTaxSquare case The GoSquare case

The GoToJailSquare case

IncomeTaxMessage is

better

Solid line

Page 16: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

16

31

Polymorphism Polymorphism 1010

• Discussion– Polymorphism is a fundamental principle in designing how a

system is organized to handle similar variations. A design based on assigning responsibilities by Polymorphism can be easily extended to handle new variations

• Guideline: When to Design with Interfaces?– Polymorphism implies the presence of abstract superclasses or

interfaces in most OO languages. – When should you consider using an interface?

• The general answer is to introduce one when you want to supportpolymorphism without being committed to a particular class hierarchy

• If an abstract superclass AC is used (without an interface), any new polymorphic solution must be a subclass of AC

– Very limiting in single-inheritance languages (e.g., Java, C#)• As a rule-of-thumb, if there is a class hierarchy with an abstract

superclass C1, consider making an interface I1 that corresponds to the public method signatures of C1, and then declare C1 to implement the I1 interface

32

Polymorphism Polymorphism 1111

• Contraindications– Sometimes, developers design systems with interfaces and

polymorphism for speculative "future-proofing" against an unknown possible variation

– It is not uncommon to see unnecessary effort being applied to future-proofing a design with polymorphism at variation points that in fact are improbable and will never actually arise

• Benefits– Extensions required for new variations are easy to add.– New implementations can be introduced without affecting

clients• Related Patterns

– Protected Variations– A number of popular GoF design patterns rely on polymorphism,

including Adapter, Command, Composite, Proxy, State, and Strategy

• Also Known As; Similar To– Choosing Message, Don't Ask "What Kind?"

Page 17: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

17

33

Pure Fabrication Pure Fabrication 11

• Problem– What object should have the responsibility, when you do not

want to violate High Cohesion and Low Coupling, or other goals, but solutions offered by Expert (for example) are not appropriate?

– There are many situations in which assigning responsibilities only to domain layer software classes leads to problems in terms of poor cohesion or coupling, or low reuse potential

• Solution– Assign a highly cohesive set of responsibilities to an artificial or

convenience class that does not represent a problem domain concept — something made up, to support high cohesion, low coupling, and reuse

– Such a class is a fabrication of the imagination. Ideally, the responsibilities assigned to this fabrication support high cohesion and low coupling, so that the design of the fabricationis very clean, or pure — hence a pure fabrication

34

Pure Fabrication Pure Fabrication 22

• Example 1– NextGen POS

• Saving a Sale Object in a Database• Support is needed to save Sale instances in a relational database. • By Information Expert, there is some justification to assign this

responsibility to the Sale class itself, because the sale has the data that needs to be saved.

• But consider the following implications – The task requires a relatively large number of supporting database-

oriented operations, none related to the concept of sale-ness, so the Sale class becomes incohesive

– The Sale class has to be coupled to the relational database interface, so its coupling goes up

– Saving objects in a relational database is a very general task for which many classes need support. Placing these responsibilities in the Sale class suggests there is going to be poor reuse or lots of duplication in other classes that do the same thing

Page 18: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

18

35

Pure Fabrication Pure Fabrication 33

• A reasonable solution is to create a new class that is solely responsible for saving objects in some kind of persistent storage medium, such as a relational database; call it the PersistentStorage.

– This class is a Pure Fabricationa figment of the imagination– PersistentStorage is not a domain concept, but something made up or

fabricated for the convenience of the software developer

• This Pure Fabrication solves the following design problems:– The Sale remains well-designed, with high cohesion and low coupling.– The PersistentStorage class is itself relatively cohesive, having the

sole purpose of storing or inserting objects in a persistent storage medium.

– The PersistentStorage class is a very generic and reusable object

36

Pure Fabrication Pure Fabrication 44

• Example 2– Monopoly Problem: Handling the Dice

• In the current design, the Player rolls all the dice and sums the total.

– Dice are very general objects, usable in many games. By putting this rolling and summing responsibility in a Monopoly game Player, the summing service is not generalized for use in other games.

– Another weakness: It is not possible to simply ask for the current dice total without rolling the dice again.

• By Pure Fabrication— we need to make something up to conveniently provide related services

– A Pure Fabrication called Cup is used to hold all the dice, roll them, and know their total.

Page 19: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

19

37

Pure Fabrication Pure Fabrication 55

DCD for a Cup

38

Pure Fabrication Pure Fabrication 66

Using the Cup in the Monopoly game

Page 20: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

20

39

Pure Fabrication Pure Fabrication 77

• Discussion– The design of objects can be broadly divided into

two groups:• Those chosen by representational decomposition

– The software class is related to or represents a thing in a domain, e.g., Sale.

• Those chosen by behavioral decomposition– Assign responsibilities by grouping behaviors or by algorithm,

without any concern for creating a class with a name or purpose that is related to a real-world domain concept, e.g., TableOfContentsGenerator

– Simply "made up" as a convenience for the object designer to group together some common behavior

– A Pure Fabrication is usually partitioned based on related functionality, so it is a kind of function-centric or behavioral object

40

Pure Fabrication Pure Fabrication 88

• Benefits– High Cohesion is supported because responsibilities are

factored into a fine-grained class that only focuses on a very specific set of related tasks.

– Reuse potential may increase because of the presence of fine-grained Pure Fabrication classes whose responsibilities have applicability in other applications

• Contraindications– Behavioral decomposition into Pure Fabrication objects is

sometimes overused by those new to object design and more familiar with decomposing or organizing software in terms of functions. To exaggerate, functions just become objects.

– There is nothing inherently wrong with creating "function" or "algorithm" objects, but it needs to be balanced with the ability to design with representational decomposition, such as the ability to apply Information Expert

Page 21: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

21

41

Pure Fabrication Pure Fabrication 99

• Contraindications– If overused, Pure Fabrication could lead to too many behavior

objects that have responsibilities not co-located with the information required for their fulfillment, which can adversely affect coupling. The usual symptom is that most of the data inside the objects is being passed to other objects to reason with it

• Related Patterns and Principles– Low Coupling.– High Cohesion.– A Pure Fabrication usually takes on responsibilities from the

domain class that would be assigned those responsibilities based on the Expert pattern.

– All GoF design patterns, such as Adapter, Command, Strategy, and so on, are Pure Fabrications.

– Virtually all other design patterns are Pure Fabrications.

42

Indirection Indirection 11

• Problem– Where to assign a responsibility, to avoid direct

coupling between two (or more) things? How to de-couple objects so that low coupling is supported and reuse potential remains higher?

• Solution– Assign the responsibility to an intermediate object

to mediate between other components or services so that they are not directly coupled.

– The intermediary creates an indirection between the other components

Page 22: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

22

43

Indirection Indirection 22

• Example– NextGen POS: TaxCalculatorAdapter

• These objects act as intermediaries to the external tax calculators. Via polymorphism, they provide a consistent interface to the inner objects and hide the variations in the external APIs.

• By adding a level of indirection and adding polymorphism, the adapter objects protect the inner design against variations in the external interfaces

44

Indirection Indirection 33

– NextGen POS Examples: PersistentStorage• The Pure Fabrication example of decoupling the Sale from the

relational database services through the introduction of a PersistentStorage class is also an example of assigning responsibilities to support Indirection. The PersistentStorage acts as a intermediary between the Sale and the database

• Discussion– "Most problems in computer science can be solved by another

level of indirection" is an old adage with particular relevance to object-oriented designs

– There is also the counter-adage: "Most problems in performance can be solved by removing another layer of indirection!"

Sale PersistentStorage

Page 23: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

23

45

Indirection Indirection 44

• Discussion– Just as many existing design patterns are specializations of

Pure Fabrication, many design patterns are also specializations of Indirection, e.g., Adapter, Facade, and Observer

– Many Pure Fabrications are generated because of Indirection. – The motivation for Indirection is usually Low Coupling; an

intermediary is added to decouple other components or services

• Benefits– Lower coupling between components.

• Related Patterns and Principles– Protected Variations– Low Coupling– Many GoF patterns, such as Adapter, Bridge, Facade, Observer,

and Mediator– Many Indirection intermediaries are Pure Fabrications

46

Protected Variations Protected Variations 11

• Problem– How to design objects, subsystems, and systems so

that the variations or instability in these elements does not have an undesirable impact on other elements?

• Solution– Identify points of predicted variation or instability;

assign responsibilities to create a stable interface around them.

– Note: The term "interface" is used in the broadest sense of an access view; it does not literally only mean something like a Java interface.

Page 24: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

24

47

Protected Variations Protected Variations 22

• Example– NextGen POS: The prior external tax calculator problem and its

solution with Polymorphism illustrate Protected Variations• The point of instability or variation is the different interfaces or

APIs of external tax calculators• By adding a level of indirection, an interface, and using

polymorphism with various ITaxCalculatorAdapter implementations, protection within the system from variations in external APIs is achieved.

• Internal objects collaborate with a stable interface; the various adapter implementations hide the variations to the external systems.

• Discussion– Protected Variations (PV) is a very important, fundamental

principle of software design!

48

Protected Variations Protected Variations 33

• Discussion (cont’d)– Almost every software or architectural design trick in book ⎯

data encapsulation, polymorphism, data-driven designs, interfaces, virtual machines, configuration files, operating systems, and much more ⎯ is a specialization of Protected Variations

– The fundamental design principle of PV is information hiding– Mechanisms Motivated by Protected Variations

• PV is a root principle motivating most of the mechanisms and patterns in programming and design to provide flexibility and protection from variations ⎯ variations in data, behavior, hardware, software components, operating systems, and more.

– The maturation of a developer or architect can be seen in their growing knowledge of ever-wider mechanisms to achieve PV, to pick the appropriate PV battles worth fighting, and their ability to choose a suitable PV solution

Page 25: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

25

49

Protected Variations Protected Variations 44

• Core Protected Variations Mechanisms– Data encapsulation, interfaces, polymorphism, indirection, and

standards are motivated by PV. – Note that components such as virtual machines and operating

systems are complex examples of indirection to achieve PV• Data-Driven Designs

– Data-driven designs cover a broad family of techniques including reading codes, values, class file paths, class names, and so forth, from an external source in order to change the behavior of, or "parameterize" a system in some way at run-time

– Other variants include style sheets, metadata for object-relational mapping, property files, reading in window layouts, and much more.

– The system is protected from the impact of data, metadata, or declarative variations by externalizing the variant, reading it in, and reasoning with it

50

Protected Variations Protected Variations 55

• Service Lookup– Service lookup includes techniques such as using naming

services (for example, Java's JNDI) or traders to obtain a service (for example, Java's Jini, or UDDI for Web services).

– Clients are protected from variations in the location of services, using the stable interface of the lookup service. It is a special case of data-driven design

• Interpreter-Driven Designs– Interpreter-driven designs include rule interpreters that

execute rules read from an external source, script or language interpreters that read and run programs, virtual machines, neural network engines that execute nets, constraint logic engines that read and reason with constraint sets, and so forth.

– This approach allows changing or parameterizing the behavior of a system via external logic expressions.

– The system is protected from the impact of logic variations by externalizing the logic, reading it in, and using an interpreter

Page 26: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

26

51

Protected Variations Protected Variations 66

• Reflective or Meta-Level Designs – An example of this approach is using the

java.beans.Introspector to obtain a BeanInfo object, asking for the getter Method object for bean property X, and calling Method.invoke.

– The system is protected from the impact of logic or external code variations by reflective algorithms that use introspection and meta-language services. It may be considered a special case of data-driven designs

• Uniform Access– Some languages, such as Ada, Eiffel, and C#, support a

syntactic construct so that both a method and field access are expressed the same way. For example, aCircle.radius may invoke a radius():float method or directly refer to a public field, depending on the definition of the class. We can change from public fields to access methods, without changing the client code

52

Protected Variations Protected Variations 77

• Standard Languages– Official language standards such as SQL provide protection

against a proliferation of varying languages• The Liskov Substitution Principle (LSP)

– LSP formalizes the principle of protection against variations indifferent implementations of an interface, or subclass extensions of a superclass

• Informally, software (methods, classes, …) that refers to a type T (some interface or abstract superclass) should work properly or as expected with any substituted implementation or subclass of T ⎯call it S. For example:

• No matter what implementation of ITaxCalculatorAdapter is passed in as an actual parameter, the method should continue to work “as expected”

public void addTaxes( ITaxCalculatorAdapter calculator, Sale sale ){

List taxLineItems = calculator.getTaxes( sale );// ...

}

Page 27: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

27

53

Protected Variations Protected Variations 88

• Don't Talk to Strangers (the Law of Demeter)– It means to avoid creating designs that traverse long object

structure paths and send messages (or talk) to distant, indirect (stranger) objects

• Such designs are fragile with respect to changes in the object structures ⎯ a common point of instability

• A mechanism to achieve protection from structure changes– Is formerly a GRASP principle and is replaced by PV which is

more general– The rule: within a method, messages should only be sent to the

following objects: • The this object (or self).• A parameter of the method.• An attribute of this.• An element of a collection which is an attribute of this.• An object created within the method.

54

Protected Variations Protected Variations 99

• Don't Talk to Strangers (cont’d)– The intent is to avoid coupling a client to knowledge of indirect

objects and the object connections between objects.– Direct objects are a client's "familiars," indirect objects are

"strangers." A client should talk to familiars, and avoid talking to strangers.

– An example that (mildly) violates Don't Talk to Strangers class Register{private Sale sale;

public void slightlyFragileMethod(){

// sale.getPayment() sends a message to a "familiar" (passes #3)

// but in sale.getPayment().getTenderedAmount()// the getTenderedAmount() message is to a "stranger" Payment

Money amount = sale.getPayment().getTenderedAmount();

// ...}

// ...}

Stranger

Page 28: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

28

55

Protected Variations Protected Variations 1010

• Don't Talk to Strangers (cont’d)– A more fragile method:

– Or more generally:

public void moreFragileMethod(){

AccountHolder holder =sale.getPayment().getAccount().getAccountHolder();

// …}

public void doX(){

F someF =foo.getA().getB().getC().getD().getE().getF();

// …}

56

Protected Variations Protected Variations 1111

• Don't Talk to Strangers (cont’d)– The above examples has a pattern: the design is coupled to a

particular structure of how objects are connected– The farther along a path the program traverses, the more

fragile it is. Why? Because the object structure (the connections) may change. This is especially true in young applications or early iterations

– Strictly obeying this law requires adding new public operations to the "familiars" of an object; these operations provide the ultimately desired information, and hide how it was obtained. For example, to support Don't Talk to Strangers for the previoustwo cases: // case 1Money amount = sale.getTenderedAmountOfPayment();

// case 2AccountHolder holder = sale.getAccountHolderOfPayment();

Page 29: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

29

57

Protected Variations Protected Variations 1212

• Contraindications ⎯ Caution: Speculative PV and Picking Your Battles– Definitions for points of change

• Variation point: Variations in the existing, current system or requirements, such as the multiple tax calculator interfaces that must be supported.

• Evolution point: Speculative points of variation that may arise in the future, but which are not present in the existing requirements

– PV is applied to both variation and evolution points• A caution: Sometimes the cost of speculative "future-proofing" at

evolution points outweighs the cost incurred by a simple, more "brittle" design that is reworked as necessary in response to the true change pressures.

• That is, the cost of engineering protection at evolution points can be higher than reworking a simple design

58

Protected Variations Protected Variations 1313

– If the need for flexibility and protection from change is realistic, then applying PV is motivated. But if it is for speculative future-proofing or speculative "reuse" with very uncertain probabilities, then restraint and critical thinking iscalled for

• Novice developers tend toward brittle designs, • Intermediate developers tend toward overly fancy and flexible,

generalized ones (in ways that never get used). • Expert designers choose with insight; perhaps a simple and brittle

design whose cost of change is balanced against its likelihood

• Benefits– Extensions required for new variations are easy to add.– New implementations can be introduced without affecting

clients.– Coupling is lowered.– The impact or cost of changes can be lowered

Page 30: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

30

59

Protected Variations Protected Variations 1414

• Related Patterns and Principles– Most design principles and patterns are mechanisms for protected

variation, including polymorphism, interfaces, indirection, data encapsulation, most of the GoF design patterns, and so on.

– Variation and evolution points are also called "hot spots”• Also Known As; Similar To

– PV is essentially the same as the information hiding and open-closed principles, which are older terms.

– As an "official" pattern in the pattern community, it was named "Protected Variations" in 1996 by Cockburn

• Parnas intended information hiding to mean hide information about the design from other modules, at the points of difficulty or likely change– Parnas's information hiding is the same principle expressed in PV, and

not simply data encapsulation ⎯ which is but one of many techniques to hide information about the design.

– However, the term has been so widely reinterpreted as a synonym for data encapsulation that it is no longer possible to use it in its original sense without misunderstanding

60

Protected Variations Protected Variations 1515

• Open-Closed Principle (OCP)– Modules should be both open (for extension; adaptable) and closed

(the module is closed to modification in ways that affect clients).– Is essentially equivalent to the PV pattern and to information hiding – OCP and PV are essentially two expressions of the same principle, with

different emphasis: protection at variation and evolution points. – In OCP, "module" includes all discrete software elements, including

methods, classes, subsystems, applications, and so forth – In the context of OCP, the phrase "closed with respect to X" means

that clients are not affected if X changes• For example, "the class is closed with respect to instance field definitions"

through the mechanism of data encapsulation with private fields and public accessing methods. At the same time, they are open to modifying the definitions of the private data, because outside clients are not directly coupled to the private data

• As another example, "the tax calculator adapters are closed with respect to their public interface" through implementing the stable ITaxCalculatorAdapter interface. However, the adapters are open to extension by being privately modified in response to changes in the APIs of the external tax calculators, in ways that do not break their clients

Page 31: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

31

Chapter 26Chapter 26Applying Applying GoFGoF

Design Patterns Design Patterns

62

GoFGoF Design PatternsDesign Patterns• Object design and the assignment of responsibilities

can be explained and learned based on the application of patterns ⎯ a vocabulary of principles and idioms that can be combined to design objects

• The Gang-of-Four Design Patterns– A seminal and extremely popular work

that presents 23 patterns useful during object design

– Not all of the 23 patterns are widely used; perhaps 15 are common and most useful

Page 32: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

32

63

Adapter (Adapter (GoFGoF) ) 11

• Name: Adapter• Problem:

– How to resolve incompatible interfaces, or provide a stable interface to similar components with different interfaces?

• Solution: (advice)– Convert the original interface of a component into another

interface, through an intermediate adapter object• NextGen POS example

– The NextGen POS system needs to support several kinds of external third-party services, including tax calculators, credit authorization services, inventory systems, and accounting systems, among others. Each has a different API, which can't be changed

– A solution is to add a level of indirection with objects that adapt the varying external interfaces to a consistent interface used within the application

64

Adapter (Adapter (GoFGoF) ) 22

TaxMasterAdapter

getTaxes( Sale ) : List of TaxLineItems

GoodAsGoldTaxProAdapter

getTaxes( Sale ) : List of TaxLineItems

«interface»ITaxCalculatorAdapter

getTaxes( Sale ) : List of TaxLineItems

Adapters use interfaces and polymorphism to add a level of indirection to varying APIs in other components.

SAPAccountingAdapter

postReceivable( CreditPayment )postSale( Sale )...

GreatNorthernAccountingAdapter

postReceivable( CreditPayment )postSale( Sale )...

«interface»IAccountingAdapter

postReceivable( CreditPayment )postSale( Sale )...

«interface»IInventoryAdapter

...

«interface»ICreditAuthorizationService

Adapter

requestApproval(CreditPayment,TerminalID, MerchantID)...

The Adapter pattern

Page 33: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

33

65

Adapter (Adapter (GoFGoF) ) 33

• Guideline: Include Pattern in Type Name– The type names include the pattern name "Adapter." This is a common

style and has the advantage of easily communicating to others reading the code or diagrams what design patterns are being used.

• Related Patterns– A resource adapter that hides an external system may also be

considered a Facade object, as it wraps access to the subsystem or system with a single object. However, the motivation to call it a resource adapter especially exists when the wrapping object provides adaptation to varying external interfaces.

AppendAdaptor

66

Some GRASP Principles as a Some GRASP Principles as a Generalization of Other Patterns Generalization of Other Patterns

• The previous use of the Adapter pattern can be viewed as a specialization of some GRASP building blocks:– Adapter supports Protected Variations with respect to changing

external interfaces or third-party packages through the use of an Indirection object that applies interfaces and Polymorphism

• A Solution to Pattern Overload– The pattern almanac 2000 lists around 500 design patterns– It's important for an experienced designer to know in detail and

by memory 50+ of the most important design patterns, but few of us can learn or remember 1,000 patterns, or even start to organize that pattern plethora into a useful taxonomy

– Solution: Most design patterns can be seen as specializations of a few basic GRASP principles

• It is even more helpful to see their underlying basic themes (Protected Variations, Polymorphism, Indirection, …) to help us to cut through the myriad details and see the essential "alphabet" of design techniques being applied

Page 34: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

34

67

Example: Adapter and GRASP Example: Adapter and GRASP

Relating Adapter to some core GRASP principles

It's the underlying themes that are important, and the fine details of Adapter or Strategy or whatever will become secondary

achieve

Is a

68

"Analysis" Discoveries During "Analysis" Discoveries During Design: Domain Model Design: Domain Model 11

• Observe that in the Adapter design in Figure 26.1, the getTaxes operation returns a list of TaxLineItems– A list of tax line items are associated with a sale, such as

• state tax, federal tax, …– In addition to being a newly created software class in the

Design Model, this is a domain concept. • It is normal and common to discover noteworthy domain concepts

and refined understanding of the requirements during design or programming

– Should this discovery be reflected in the Domain Model (or Glossary)?

• If the Domain Model will be used in the future as a source of inspiration for later design work, or as a visual learning aid to communicate the key domain concepts, then adding it could have value

Page 35: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

35

69

"Analysis" Discoveries During "Analysis" Discoveries During Design: Domain Model Design: Domain Model 22

Updated partial Domain Model

70

Factory Factory 11

• This is also called Simple Factory or Concrete Factory– This pattern is NOT a GoF design pattern, but extremely

widespread. – It is also a simplification of the GoF Abstract Factory pattern,

and often described as a variation of Abstract Factory, althoughthat's not strictly accurate

• The adapter raises a new problem in the design: – Who creates the adapters?– How to determine which class of adapter to create, such as

TaxMaster-Adapter or GoodAsGoldTaxProAdapter?• If some domain object creates them

– The responsibilities of the domain object are going beyond pure application logic and into other concerns related to connectivity with external software components

– This point underscores another fundamental design principle (usually considered an architectural design principle): Design to maintain a separation of concerns.

Page 36: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

36

71

Factory Factory 22

• Design to maintain a separation of concerns– Modularize or separate distinct concerns into different areas, so that

each has a cohesive purpose – Is an application of the GRASP High Cohesion principle

• Choosing a domain object (such as a Register) to create the adapters does not support the goal of a separation of concerns, and lowers its cohesion

• A common alternative in this case is to apply the Factory pattern, in which a Pure Fabrication "factory" object is defined to create objects.

• Factory objects have several advantages:– Separate the responsibility of complex creation into cohesive helper

objects.– Hide potentially complex creation logic.– Allow introduction of performance-enhancing memory management

strategies, such as object caching or recycling.

72

Factory Factory 33

The Factory pattern

Page 37: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

37

73

Factory Factory 44

• Name: Factory• Problem:

– Who should be responsible for creating objects when there are special considerations, such as complex creation logic, a desireto separate the creation responsibilities for better cohesion, and so forth?

• Solution: (advice)– Create a Pure Fabrication object called a Factory that handles

the creation• Note

– In the ServicesFactory, the logic to decide which class to create is resolved by reading in the class name from an external source (e.g., via a system property) and then dynamically loading the class

– This is an example of a partial data-driven design. – This design achieves Protected Variations with respect to

changes in the implementation class of the adapter• Related Patterns

– Factories are often accessed with the Singleton pattern

74

Singleton (Singleton (GoFGoF) ) 11

• The ServicesFactory raises another new problem in the design: – Who creates the factory itself, and how is it accessed?– First, observe that only one instance of the factory is needed

within the process. – Second, the methods of this factory may need to be called

from various places in the code, as different places need access to the adapters for calling on the external services.

• Thus, there is a visibility problem: How to get visibility to this single ServicesFactory instance?

• One solution is pass the ServicesFactory instance around as a parameter to wherever a visibility need is discovered for it, or

– To initialize the objects that need visibility to it, with a permanent reference. This is possible but inconvenient;

• An alternative is the Singleton pattern: global visibility or a single access point to a single instance of a class

Page 38: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

38

75

Singleton (Singleton (GoFGoF) ) 22

• Name: Singleton• Problem:

– Exactly one instance of a class is allowed ⎯ it is a "singleton." Objects need a global and single point of access.

• Solution: (advice)– Define a static method of the class that returns the singleton.

• Applying UML– Notice how a singleton is illustrated, with a '1' in the top right

corner of the name compartment.• The key idea is that class X defines a static method

getInstance that itself provides a single instance of X.– With this approach, a developer has global visibility to this

single instance, via the static getInstance method of the class

76

Singleton (Singleton (GoFGoF) ) 33

Page 39: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

39

77

Singleton (Singleton (GoFGoF) ) 44

• Since visibility to public classes is global in scope (in most languages), at any point in the code, in any method of any class, one can write SingletonClass.getInstance() in order to obtain visibility to the singleton instance, and then send it a message, such as SingletonClass.getInstance().doFoo().

public class Register{

public void initialize(){

… do some work …

// accessing the singleton Factory via the getInstance callaccountingAdapter =

ServicesFactory.getInstance().getAccountingAdapter();

… do some work …}

// other methods…

} // end of class

78

Singleton (Singleton (GoFGoF) ) 55

• Implementation and Design Issues– A Singleton getInstance method is often frequently called. – In multi-threaded applications

• The creation step of the lazy initialization logic is a critical sectionrequiring thread concurrency control.

• Thus, assuming the instance is lazy initialized, it is common towrap the method with concurrency control. In Java, for example:

public static synchronized ServicesFactory getInstance(){

if ( instance == null ){

// critical section if multithreaded applicationinstance = new ServicesFactory();

}return instance;

}

Page 40: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

40

79

Singleton (Singleton (GoFGoF) ) 66

• Why not prefer eager initialization, as in this example? public class ServicesFactory{

// eager initializationprivate static ServicesFactory instance = new ServicesFactory();

public static ServicesFactory getInstance(){

return instance;}

// other methods...

}

• Lazy initialization is usually preferred for at least these reasons:– Creation work (and perhaps holding on to "expensive" resources) is

avoided, if the instance is never actually accessed.– The getInstance lazy initialization sometimes contains complex and

conditional creation logic.

80

Singleton (Singleton (GoFGoF) ) 77

• Why not make all the service methods static methods of the class itself, instead of using an instance object with instance-side methods?

• An instance and instance-side methods are usually preferred for these reasons:– Instance-side methods permit subclassing and refinement of the

singleton class into subclasses; static methods are not polymorphic(virtual) and don't permit overriding in subclasses in most languages (Smalltalk excluded).

– Most object-oriented remote communication mechanisms (for example, Java's RMI) only support remote-enabling of instance methods, not static methods. A singleton instance could be remote-enabled, although that is admittedly rarely done.

– A class is not always a singleton in all application contexts. In application X, it may be a singleton, but it may be a "multi-ton" in application Y. It is also not uncommon to start off a design thinking the object will be a singleton, and then discovering a need for multiple instances in the same process. Thus, the instance-side solution offers flexibility.

Page 41: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

41

81

Singleton (Singleton (GoFGoF) ) 88

• Related Patterns– The Singleton pattern is often used for Factory objects and

Facade objects ⎯ another GoF pattern that will be discussed

Implicit getInstance Singleton pattern message indicated in the UML because of the '1' mark

82

Conclusion of the External Services Conclusion of the External Services with Varying Interfaces Problem with Varying Interfaces Problem 11

• A combination of Adapter, Factory, and Singleton patterns have been used to provide Protected Variations from the varying interfaces of external tax calculators, accounting systems, and so forth

• This case study (Figure 26.8) is to illustrate that at least a design can be constructed from a set of principles or pattern "building blocks," and that there is a methodical approach to doing and explaining a design.

• Object designers can use patterns and pattern names supports raising the level of abstraction in design communication or documentation. For example, – To handle the problem of varying interfaces for external services, let's

use Adapters generated from a Singleton Factory."

Page 42: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

42

83

Conclusion of the External Services Conclusion of the External Services with Varying Interfaces Problem with Varying Interfaces Problem 22

Adapter, Factory, and Singleton patterns applied to the design

84

Strategy (Strategy (GoFGoF) ) 11

• The pricing strategy (which may also be called a rule, policy, or algorithm) for a sale can vary. – During one period it may be 10% off all sales, later it may be

$10 off if the sale total is greater than $200, and myriad other variations.

– How do we design for these varying pricing algorithms?

• Name: Strategy• Problem:

– How to design for varying, but related, algorithms or policies? How to design for the ability to change these algorithms or policies?

• Solution: (advice)– Define each algorithm/policy/strategy in a separate class, with

a common interface

Page 43: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

43

85

Strategy (Strategy (GoFGoF) ) 22

• Since the behavior of pricing varies by the strategy (or algorithm), we create multiple SalePricingStrategy classes, each with a polymorphic getTotal method

Pricing Strategy classes

86

Strategy (Strategy (GoFGoF) ) 33

• A strategy object is attached to a context object ⎯the object to which it applies the algorithm. – In this example, the context object is a Sale.

• When a getTotal message is sent to a Sale, it delegates some of the work to its strategy object – It is not required that the message to the context object and

the strategy object have the same name, as in this example (for example, getTotal and getTotal), but it is common.

– It is common that the context object pass a reference to itself (this) on to the strategy object, so that the strategy has parameter visibility to the context object, for further collaboration

Page 44: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

44

87

Strategy (Strategy (GoFGoF) ) 44

Strategy in collaboration

Observe that the context object (Sale) needs attribute visibility to its strategy

88

Strategy (Strategy (GoFGoF) ) 55

• Creating a Strategy with a Factory – There are different pricing algorithms or strategies, and they

change over time. – Who should create the strategy?

• Apply the Factory pattern again– A PricingStrategyFactory can be responsible for creating all strategies

(all the pluggable or changing algorithms or policies) needed by the application

• As with the ServicesFactory, it can read the name of the implementation class of the pricing strategy from a system property (or some external data source), and then make an instance of it.

• With this partial data-driven design (or reflective design) one can dynamically change at any time

Page 45: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

45

89

Strategy (Strategy (GoFGoF) ) 66

• Observe the reference via a directed association is to the interfaceISalePricingStrategy, not to a concrete class. – This indicates that the reference attribute in the Sale will be declared

in terms of the interface, not a class, so that any implementation of the interface can be bound to the attribute

Context object needs attribute visibility to its strategy

90

Strategy (Strategy (GoFGoF) ) 77

• Note that because of the frequently changing pricing policy (it could be every hour), it is not desirable to cache the created strategy instance in a field of the PricingStrategyFactory, but rather to re-create one each time, by reading the external property for its class name, and then instantiating the strategy

Factory for strategies

Page 46: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

46

91

Strategy (Strategy (GoFGoF) ) 88

• When a Sale instance is created, it can ask the factory for its pricing strategy

Creating a strategy

92

Strategy (Strategy (GoFGoF) ) 99

• Reading and Initializing the Percentage Value – How to find the different numbers for the percentage or

absolute discounts?• For example, on Monday, the PercentageDiscountPricingStrategy

may have a percentage value of 10%, but 20% on Tuesday.• These numbers will be stored in some external data store, such as

a relational database, so they can be easily changed – A reasonable choice is the StrategyFactory itself, since it is

creating the pricing strategy, and can know which percentage to read from a data store ("current store discount," "senior discount," and so forth)

• Designs to read these numbers from external data stores vary from the simple to the complex, such as a plain JDBC SQL call or collaborating with objects

– Analyzing the variation and evolution points with respect to the data store will reveal if there is a need for protected variation

• Related Patterns– Strategy is based on Polymorphism, and provides Protected Variations

with respect to changing algorithms. Strategies are often created by a Factory

Page 47: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

47

93

Composite (Composite (GoFGoF) and Other ) and Other Design Principles Design Principles 11

• How do we handle the case of multiple, conflicting pricing policies?– For example, suppose a store has the following policies in

effect today (Monday):• 20% senior discount policy• preferred customer discount of 15% off sales over $400• on Monday, there is $50 off purchases over $500• buy 1 case of Darjeeling tea, get 15% discount off of everything

– Suppose a senior who is also a preferred customer buys 1 case of Darjeeling tea, and $600 of veggieburgers. What pricing policy should be applied?

– To clarify: There are now pricing strategies that attach to the sale by virtue of three factors:

• time period (Monday)• customer type (senior)• a particular line item product (Darjeeling tea)

94

Composite (Composite (GoFGoF) and Other ) and Other Design Principles Design Principles 22

• Part of the answer to this problem requires defining the store'sconflict resolution strategy– For example, "best for the customer" (lowest price) conflict resolution

strategy, or– Use a "highest price" strategy during a difficult financial period

• The things need to note for dealing with this problem– There can exist multiple co-existing strategies– A pricing strategy can be related to the type of customer

• This has creation design implications: The customer type must be known by the StrategyFactory at the time of creation of a pricing strategy for the customer

– A pricing strategy can be related to the type of product being bought (for example, Darjeeling tea)

• The ProductDescription must be known by the StrategyFactory at the time of creation of a pricing strategy influenced by the product

• Is there a way to change the design so that the Sale object does not know if it is dealing with one or many pricing strategies, and also offer a design for the conflict resolution? – Yes, with the Composite pattern.

Page 48: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

48

95

Composite (Composite (GoFGoF) and Other ) and Other Design Principles Design Principles 33

• Name: Composite• Problem:

– How to treat a group or composition structure of objects the same way (polymorphically) as a non-composite (atomic) object?

• Solution: (advice)– Define classes for composite and atomic objects so that they

implement the same interface.

• Example– POS: a new class called

CompositeBestForCustomerPricingStrategy (can implement the ISalesPricingStrategy and itself contain other ISalesPricingStrategy objects

96

Composite (Composite (GoFGoF) and Other ) and Other Design Principles Design Principles 44

The Composite pattern

The outer composite object contains a list of inner objects, and both the outer and inner objects implement the same interface

Original design

Page 49: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

49

97

Composite (Composite (GoFGoF) and Other ) and Other Design Principles Design Principles 55

We can attach either a composite CompositeBestForCustomerPricingStrategy object or a PercentDiscountPricingStrategy object to the Sale object, and the Sale does not know or care if its pricing strategy is an atomic or composite strategy — it looks the same to the Sale object

98

Composite (Composite (GoFGoF) and Other ) and Other Design Principles Design Principles 66

// a Composite Strategy that returns the lowest total// of its inner SalePricingStrategies

public class CompositeBestForCustomerPricingStrategyextends CompositePricingStrategy

{

public Money getTotal( Sale sale ){

Money lowestTotal = new Money( Integer.MAX_VALUE );

// iterate over all the inner strategies

for (Iterator i = strategies.iterator(); i.hasNext();){

ISalePricingStrategy strategy =(ISalePricingStrategy)i.next();

Money total = strategy.getTotal( sale );lowestTotal = total.min( lowestTotal );

}return lowestTotal;

}

} // end of class

// superclass so all subclasses can inherit a List of strategies

public abstract class CompositePricingStrategy

implements ISalePricingStrategy{

protected List strategies = new ArrayList();

public add( ISalePricingStrategy s ){

strategies.add( s );}

public abstract MoneygetTotal(Sale sale);

} // end of class

Sample code in Java, the CompositePricingStrategy and one of its subclasses

Page 50: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

50

99

Composite (Composite (GoFGoF) and Other ) and Other Design Principles Design Principles 77

Abstract superclasses, abstract methods, and inheritance in the UML

100

Composite (Composite (GoFGoF) and Other ) and Other Design Principles Design Principles 88

• When do we create the Multiple SalePricingStrategies?– A desirable design will start by creating a Composite that

contains the present moment's store discount policy (which could be set to 0% discount if none is active), such as some PercentageDiscountPricingStrategy.

– Then, if at a later step in the scenario, another pricing strategy is discovered to also apply (such as senior discount), it will be easy to add it to the composite, using the inherited CompositePricingStrategy.add method

– There are three points in the scenario where pricing strategies may be added to the composite:

• Current store-defined discount, added when the sale is created.• Customer type discount, added when the customer type is

communicated to the POS.• Product type discount (if bought Darjeeling tea, 15% off the

overall sale), added when the product is entered to the sale.

Page 51: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

51

101

Composite (Composite (GoFGoF) and Other ) and Other Design Principles Design Principles 99

:Sale

1:PricingStrategyFactory

ps =getSale

PricingStrategy

:Register

makeNewSale create

create ps :CompositeBestForCustomerPricingStrategy

create( percent ) s : PercentageDiscountPricingStrategy

add( s )

Creating a composite strategy

Current store-defined discount, added when the sale is created

psstored

May be 0

102

Composite (Composite (GoFGoF) and Other ) and Other Design Principles Design Principles 1010

• Adding customer type discount– Consider the use case extension

Use Case UC1: Process Sale …Extensions (or Alternative Flows):5b. Customer says they are eligible for a discount (e.g.,

employee, preferred customer)1. Cashier signals discount request.2. Cashier enters Customer identification.3. System presents discount total, based on discount rules

• This indicates a new system operation on the POS system is required– We will call this fifth system operation

enterCustomerForDiscount; it may optionally occur after the endSale operation

– Some form of customer identification, such as customerID, is needed

Page 52: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

52

103

Composite (Composite (GoFGoF) and Other ) and Other Design Principles Design Principles 1111

Creating the pricing strategy for a customer discount, part 1.

New system

operation

104

Composite (Composite (GoFGoF) and Other ) and Other Design Principles Design Principles 1212

s :Sale

1:PricingStrategy

Factory

addCustomerPricingStrategy( s )

ps :CompositeBestForCustomerPricingStrategy

create( pct ) s : PercentageDiscountPricingStrategyadd( s )

by Expert

enterCustomerForDiscount( c : Customer )

c = getCustomer

by Factory and High Cohesion

by Expert ps = getPricingStrategy

pct = getCustomer

Percentage( c )

by High Cohesion

by Factory and Composite

Pass Aggregate Object as Parameter

sd Enter Customer For Discount

Creating the pricing strategy for a customer discount, part 2

Page 53: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

53

105

Composite (Composite (GoFGoF) and Other ) and Other Design Principles Design Principles 1313

• Considering GRASP and Other Principles in the Design – Let Sale send a message to the PricingStrategyFactory

• By Low Coupling (eliminate the couple between Register and PricingStrategyFactory) and Information Expert (Sale knows its current pricing strategy)

– Let Register asking the Store for a Customer, given an ID. • By Information Expert (Store knows all the Customers) and Low

Coupling (Register already has attribute visibility to the Store)

• IDs to Objects (pattern)– This is a common practice in object design — to transform keys

and IDs for things into true objects. • This transformation often takes place shortly after an ID or key

enters the domain layer of the Design Model from the UI layer – A true Customer object

• Encapsulates a set of information about the customer• Can have behavior (related to Information Expert, for example)• Frequently becomes beneficial and flexible as the design grows

106

Composite (Composite (GoFGoF) and Other ) and Other Design Principles Design Principles 1414

• Pass Aggregate Object as Parameter (pattern)– In the addCustomerPricingStrategy(s:Sale) message we pass a

Sale to the factory, and then the factory turns around and asks for the Customer and PricingStrategy from the Sale. Why?

– A common object design idiom: Avoid extracting child objects out of parent or aggregate objects, and then passing around the child objects. Rather, pass around the aggregate object that contains child objects

– Following this principle increases flexibility, because then the factory can collaborate with the entire Sale in ways we may not have previously anticipated as necessary (which is very common), and as a corollary, it reduces the need to anticipate what the factory object needs

• Related Patterns– Composite is often used with the Strategy and Command

patterns. Composite is based on Polymorphism and provides Protected Variations to a client so that it is not impacted if its related objects are atomic or composite

Page 54: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

54

107

Facade (Facade (GoFGoF) ) 11

• Another requirement chosen for this iteration is pluggable business rules– Can occur at predictable points in the scenarios, such as when

makeNewSale or enterItem• Assume that rules are desired that can invalidate an

action. For example:– Suppose when a new sale is created, it is possible to identify

that it will be paid by a gift certificate. Then, a store may have a rule to only allow one item to be purchased if a gift certificate is used.

– If the sale is paid by a gift certificate, invalidate all payment types of change due back to the customer except for another gift certificate

– Suppose when a new sale is created, it is possible to identify that it is for a charitable donation (from the store to the charity). A store may also have a rule to only allow item entries less than $250 each, and also to only add items to the sale if the currently logged in "cashier" is a manager

108

Facade (Facade (GoFGoF) ) 22

• Suppose that the software architect wants a design that has low impact on the existing software components – Architect wants to design for a separation of concerns, and

factor out this rule handling into a separate concern. – Suppose that the architect is unsure of the best

implementation for this pluggable rule handling, and may want to experiment with different solutions for representing, loading, and evaluating the rules

• For example, rules can be implemented with the Strategy pattern or with rule interpreters

– To solve this design problem, the Facade pattern can be used

Page 55: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

55

109

Facade (Facade (GoFGoF) ) 33

• Name: Façade• Problem:

– A common, unified interface to a disparate set of implementations or interfaces, such as within a subsystem, is required. There may be undesirable coupling to many things in the subsystem, or the implementation of the subsystem may change. What to do?

• Solution: (advice)– Define a single point of contact to the subsystem — a facade

object that wraps the subsystem. This facade object presents a single unified interface and is responsible for collaborating with the subsystem components

110

Facade (Facade (GoFGoF) ) 44

• A Facade is a "front-end" object that is the single point of entry for the services of a subsystem– The implementation and other components of the subsystem

are private and can't be seen by external components. – Facade provides Protected Variations from changes in the

implementation of a subsystem.

• NextGEN POS example: we will define a "rule engine" subsystem, whose specific implementation is not yet known – The facade object to this subsystem will be called

POSRuleEngineFacade (see the Figure 26.20 in next side)– The designer decides to place calls to this facade near the start

of the methods that have been defined as the points for pluggable rules

Page 56: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

56

111

Facade (Facade (GoFGoF) ) 55

UML package diagram with a Facade

112

Facade (Facade (GoFGoF) ) 66

• Note the use of the Singleton pattern. Facades are often accessed via Singleton

• With this design, the complexity and implementation of how rules will be represented and evaluated are hidden in the "rules engine" subsystem, accessed via the POSRuleEngineFacade facade

public class Sale{

public void makeLineItem( ProductDescription desc, int quantity ){

SalesLineItem sli = new SalesLineItem( desc, quantity );

// call to the Facadeif ( POSRuleEngineFacade.getInstance().isInvalid( sli, this ) )

return;

lineItems.add( sli );}// ...

} // end of class

Page 57: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

57

113

Facade (Facade (GoFGoF) ) 66

• With Façade, a separation of concerns has been achieved to some degree– All the rule-handling concerns have been delegated to another

subsystem

• Related Patterns– Facades are usually accessed via the Singleton pattern. They

provide Protected Variations from the implementation of a subsystem, by adding an Indirection object to help support Low Coupling. External objects are coupled to one point in a subsystem: the facade object.

– In the Adapter pattern, an adapter object is a kind of façade, because it is used to wrap access to external systems with varying interfaces. But the emphasis is to provide adaptation to varying interfaces, and thus it is more specifically called an adapter

114

Observer/PublishObserver/Publish--Subscribe/Delegation Subscribe/Delegation Event Model (Event Model (GoFGoF)) 11

• Another requirement for the iteration is adding the ability for a GUI window to refresh its display of the sale total when the total changes

Goal: When the total of the sale changes, refresh the display with the new value

Sale

total...

setTotal( newTotal )...

Page 58: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

58

115

Observer/PublishObserver/Publish--Subscribe/Delegation Subscribe/Delegation Event Model (Event Model (GoFGoF)) 22

• Why not do the following as a solution? When the Sale changes its total, the Sale object sends a message to a window – Violate the Model-View Separation principle

• Model-View Separation principle states that – Model objects (e.g, Sale) should not know about view or

presentation objects. It promotes Low Coupling from other layers to the presentation (UI) layer of objects

– Model-View Separation supports Protected Variations with respect to a changing user interface.

• To solve this design problem, the Observer pattern can be used.

unidirectionalModel

Presentation(view)

116

Observer/PublishObserver/Publish--Subscribe/Delegation Subscribe/Delegation Event Model (Event Model (GoFGoF)) 33

• Name: Observer (Publish-Subscribe)• Problem:

– Different kinds of subscriber objects are interested in the state changes or events of a publisher object, and want to react in their own unique way when the publisher generates an event. Moreover, the publisher wants to maintain low coupling to the subscribers. What to do?

• Solution: (advice)– Define a "subscriber" or "listener" interface.

Subscribers implement this interface. The publisher can dynamically register subscribers who are interested in an event and notify them when an event occurs

Page 59: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

59

117

Observer/PublishObserver/Publish--Subscribe/Delegation Subscribe/Delegation Event Model (Event Model (GoFGoF)) 55

• The major ideas and steps in this example:– An interface is defined; in this case, PropertyListener with the

operation onPropertyEvent.– Define the window to implement the interface.

• SaleFrame1 will implement the method onPropertyEvent.– When the SaleFrame1 window is initialized, pass it the Sale

instance from which it is displaying the total.– The SaleFrame1 window registers or subscribes to the Sale

instance for notification of "property events," via the addPropertyListener message. That is, when a property (such as total) changes, the window wants to be notified.

– Note that the Sale does not know about SaleFrame1 objects; rather, it only knows about objects that implement the PropertyListener interface. This lowers the coupling of the Sale to the window ⎯ the coupling is only to an interface, not to a GUI class.

– The Sale instance is thus a publisher of "property events." When the total changes, it iterates across all subscribing PropertyListeners, notifying each.

118

Observer/PublishObserver/Publish--Subscribe/Delegation Subscribe/Delegation Event Model (Event Model (GoFGoF)) 44

«interface»PropertyListener

onPropertyEvent( source, name, value )

SaleFrame1

onPropertyEvent( source, name, value )

initialize( Sale sale )...

javax.swing.JFrame

...setTitle()setVisible()...

{ if ( name.equals("sale.total") ) saleTextField.setText( value.toString() );}

Sale

addPropertyListener( PropertyListener lis )publishPropertyEvent( name, value )

setTotal( Money newTotal )...

*propertyListeners

{ total = newTotal; publishPropertyEvent( "sale.total", total ); }

{ propertyListeners.add( lis );}

{ for each PropertyListener pl in propertyListeners pl.onPropertyEvent( this, name, value ); }

{ sale.addPropertyListener( this ) ... }

The Observer pattern

Page 60: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

60

119

Observer/PublishObserver/Publish--Subscribe/Delegation Subscribe/Delegation Event Model (Event Model (GoFGoF)) 66

The observer SaleFrame1 subscribes to the publisher Sale

• The SaleFrame1 object is the observer/subscriber/listener, it subscribes to interest in property events of the Sale, which is a publisher of property events

120

Observer/PublishObserver/Publish--Subscribe/Delegation Subscribe/Delegation Event Model (Event Model (GoFGoF)) 77

• When the Sale total changes, it iterates across all its registered subscribers, and "publishes an event" by sending the onPropertyEvent message to each

The Sale publishes a property event to all its subscribers

Page 61: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

61

121

Observer/PublishObserver/Publish--Subscribe/Delegation Subscribe/Delegation Event Model (Event Model (GoFGoF)) 88

The subscriber SaleFrame1 receives notification of a published event

• The onPropertyEvent message is polymorphic; the specific cases of polymorphic implementation will be shown in other diagrams

122

Observer/PublishObserver/Publish--Subscribe/Delegation Subscribe/Delegation Event Model (Event Model (GoFGoF)) 99

• In this Observer pattern, there is still some couplingfrom the model object to the view object (from the Sale to the SaleFrame1). – But it is a loose coupling to an interface independent of the

presentation layer ⎯ the PropertyListener interface. • The design does not require any subscriber objects to

actually be registered with the publisher (no objects have to be listening). – That is, the list of registered PropertyListeners in the Sale can

be empty– Coupling to a generic interface of objects that do not need to

be present, and which can be dynamically added (or removed), supports low coupling

– Protected Variations with respect to a changing user interfacehas been achieved through the use of an interface and polymorphism

Page 62: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

62

123

Observer/PublishObserver/Publish--Subscribe/Delegation Subscribe/Delegation Event Model (Event Model (GoFGoF)) 1010

• Why Is It Called Observer, Publish-Subscribe, or Delegation Event Model?– Originally, this idiom was called publish-subscribe, and it is still

widely known by that name. One object "publishes events," and objects that are interested, "subscribe" or register to interest in an event by asking the publishing to notify them

– It has been called Observer because the listener or subscriber is observing the event; that term was popularized in Smalltalk in the early 1980s

– It has also been called the Delegation Event Model (in Java) because the publisher delegates handling of events to "listeners" (subscribers)

124

Observer/PublishObserver/Publish--Subscribe/Delegation Subscribe/Delegation Event Model (Event Model (GoFGoF)) 1111

«interface»PropertyListener

onPropertyEvent( source, name, value )

SaleFrame1

onPropertyEvent( source, name, value )

initialize( Sale sale )...

javax.swing.JFrame

...setTitle()setVisible()...

Sale

addPropertyListener( PropertyListener lis )publishPropertyEvent( name, value )

setTotal( Money newTotal )...

*propertyListeners

publishes events to observers/listeners/subscribersregisters them when they ask to subscribe

listens for eventsobserves eventssubscribes to notification of events

Who is the observer, listener, subscriber, and publisher?

Page 63: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

63

125

Observer/PublishObserver/Publish--Subscribe/Delegation Subscribe/Delegation Event Model (Event Model (GoFGoF)) 1212

• Observer Is Not Only for Connecting UIs and Model Objects– The most prevalent use of this pattern is for GUI widget event

handling, in both Java technologies (AWT and Swing) and in Microsoft's .NET

– Each widget is a publisher of GUI-related events, and other objects can subscribe to interest in these.

• For example, a Swing JButton publishes an "action event" when it is pressed. Another object will register with the button so that when it is pressed, the object is sent a message and can take some action

• The AlarmClock example (next slide) is illustrative in that it emphasizes that many classes can implement the AlarmListenerinterface, many objects can simultaneously be registered listeners, and all can react to the "alarm event" in their own unique way

126

Observer/PublishObserver/Publish--Subscribe/Delegation Subscribe/Delegation Event Model (Event Model (GoFGoF)) 1313

«interface»AlarmListener

onAlarmEvent( source, time )

Beeper

onAlarmEvent( source, time )...

{ display notification dialog box }

AlarmClock

addAlarmnListener( AlarmListener lis )publishAlarmEvent( time )

setTime( newTime )...

*alarmListeners

{ time = newTime; if ( time == alarmTime ) publishAlarmEvent( time ); }

{ alarmListeners.add( lis );}

{ for each AlarmListener al in alarmListeners al.onAlarmEvent( this, time ); }

AlarmWindow

onAlarmEvent( source, time )...

javax.swing.JFrame

...setTitle()setVisible()...

ReliabilityWatchDog

onAlarmEvent( source, time )...

{ beep }

{ check that all required processes are executing normally }

Observer applied to alarm events, with different subscribers

a publisher of alarm events and various subscribers

Page 64: PART 4 Elaboration Iteration 2 – More Patternswkchen/courses/ooad/ooad952/slides22-26.pdf4 Chapter 23 Quick Analysis Update 8 Case Study: NextGen POS 1 • Objectives – Quickly

64

127

Observer/PublishObserver/Publish--Subscribe/Delegation Subscribe/Delegation Event Model (Event Model (GoFGoF)) 1414

• Implementation: Events– In both the Java and C# .NET, an "event" is communicated via a

regular message, such as onPropertyEvent. – Moreover, the event is defined as a class, and filled with

appropriate event data. The event is then passed as a parameter in the event message

class PropertyEvent extends Event{

private Object sourceOfEvent;private String propertyName;private Object oldValue;private Object newValue;//...

}class Sale{

private void publishPropertyEvent(String name, Object old, Object new ){

PropertyEvent evt = new PropertyEvent( this, "sale.total", old, new);

for each AlarmListener al in alarmListenersal.onPropertyEvent( evt );

}

//...}

128

Observer/PublishObserver/Publish--Subscribe/Delegation Subscribe/Delegation Event Model (Event Model (GoFGoF)) 1515

• Implementation: Java– When the JDK 1.0 was released in January 1996, it contained a

weak publish-subscribe implementation based on a class and interface called Observable and Observer, respectively (copied from Smalltalk)

– In late 1996, as part of the JDK 1.1 effort, the Observable-Observer design was effectively replaced by the more robust Java Delegation Event Model (DEM) version of publish-subscribe

• Related Patterns– Observer is based on Polymorphism, and provides Protected

Variations in terms of protecting the publisher from knowing the specific class of object, and number of objects, that it communicates with when the publisher generates an event.