程序代写代做代考 flex interpreter chain algorithm Software Design and Construction 1 SOFT2201 / COMP9201

Software Design and Construction 1 SOFT2201 / COMP9201
Behavioural Design Patterns
Dr. Xi Wu
School of Computer Science
The University of Sydney
Page 1

Copyright warning
COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969 WARNING
This material has been reproduced and communicated to you by or on behalf of the University of Sydney
pursuant to Part VB of the Copyright Act 1968 (the Act).
The material in this communication may be subject to copyright under the Act. Any further copying or communication of this material by you may be the subject of copyright protection under
the Act.
Do not remove this notice.
The University of Sydney Page 2

Agenda
– Behavioral Design Patterns – Strategy
– State
The University of Sydney Page 3

Behavioural Design Patterns
The University of Sydney Page 4

Behavioural Patterns
– Concerned with algorithms and the assignment of responsibilities between objects
– Describe patterns of objects and class, and communication between them
– Simplify complex control flow that’s difficult to follow at run-time
– Concentrate on the ways objects are interconnected – Behavioural Class Patterns (SOFT3202)
– Use inheritance to distribute behavior between classes (algorithms and computation) – Behavioural Object Patterns
– Use object composition, rather than inheritance. E.g., describing how group of peer objects cooperate to perform a task that no single object can carry out by itself
– Question: how peer objects know about each other?
The University of Sydney Page 5

Behavioural Patterns (GoF)
Pattern Name
Description
Strategy
Define a family of algorithms, encapsulate each one, and make them interchangeable (let algorithm vary independently from clients that use it)
Observer
Define a one-to-many dependency between objects so that when one object changes, all its dependents are notified and updated automatically
Memento
Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later
Command
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations
State
Allow an object to alter its behaviour when its internal state changes. The object will appear to change to its class
Visitor
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates
Other patterns
Interpreter, Iterator, Mediator, Chain of Responsibility, Template Method
The University of Sydney Page 6

Strategy Design Pattern
Object Behavioural Pattern
Algorithm design through encapsulation
The University of Sydney Page 7

Strategy Design Pattern
– Purpose/Intent
– Defineafamilyofalgorithms,encapsulateeachone,andmakethem
– –
interchangeable
– Letthealgorithmvaryindependentlyfromclientsthatuseit
Known as
– Policy Motivation Scenario
– Designforvaryingbutrelatedalgorithmsthataresuitablefordifferentcontexts • Abilitytochangethesealgorithms
The University of Sydney Page 8

Strategy – Applicability
– Many related classes differ only in their behavior
– You need different variant of an algorithm
– An algorithm uses data that should be hidden from its clients
– A class defines many behaviors that appear as multiple statements in its operations
The University of Sydney
Page 9

Strategy – Example (Text Viewer)
– Many algorithms for breaking a stream of text into lines
– Problem: hard-wiring all such algorithms into the classes that require them
– More complex and harder to maintain clients (more line breaking algorithms)
– Not all algorithms will be needed at all times
The University of Sydney Page 10

Strategy – Structure
strategy
Context
ContextInterface()
Strategy
Algorithm()
ConcreteStrategyA
Algorithm()
ConcreteStrategyB
ConcreteStrategyC
The University of Sydney
Page 11
Algorithm()
Algorithm()

Strategy – Example (Text Viewer)
Maintain & update the line breaks of text
The University of Sydney
Page 12
Different line breaking algorithms (strategies)

Strategy – Participants
Participant
Goals
Strategy (Compositor)
Declares an interface common to all supported algorithms Used by context to call the algorithm defined by ConcereteStrategy
ConcereteStrategy (SimpleCompositor, TeXCompositor, etc)
Implements the algorithm using the Strategy interface
Context (Composition)
Is configured with a ConcereteStrategy object
Maintains a reference to a Strategy object
May define an interface that lets Strategy access its data
The University of Sydney Page 13

Strategy – Collaborations
– Strategy and Context interact to implement the chosen algorithm
– A context may pass all data required by the algorithm to the Strategy
– The context can pass itself as an argument to Strategy operations
– A context forwards requests from its clients to its strategy
– Clients usually create and pass a ConcreteStrategy object to the context;
thereafter, clients interact with the context exclusively
The University of Sydney
Page 14

Strategy – Consequences (Benefits)
– Family of related algorithms (behaviors) for context to reuse
– Alternative to sub-classing
– Whynotsub-classingaContextclassdirectlytogiveitdifferentbehaviors?
– Strategies eliminate conditional statements
– Provide choice of different implementation of the same behavior
The University of Sydney
Page 15

Strategy – Consequences (Drawbacks)
– Clients must be aware of different strategies – Understandhowstrategiesdiffer
– Communicate overhead between Strategy and Context
– StrategyinterfaceissharedbyallConcereteStrategyclasseswhetherthe
algorithms they implement are trivial or complex
– Increased number of objects in an application
– Can be reduced by implementing strategies as stateless objects that context can share
– Strategyobjectsoftenmakegoodflyweight(sharingstrategies)
The University of Sydney Page 16

Strategy – NextGen PoS System
– Design problem: how to provide more complex pricing logic, e.g., store- wide discount for the day, senior citizen discounts
– The pricing strategy (or policy) for a sale can vary: – 10%ofallsalesduringaspecificperiod
– $10offifthetotalsaleisgreaterthan$200
– Other variations
– How do we design our system to accommodate such varying pricing policies?
The University of Sydney
Page 17

NextGen PoS – Pricing Strategy Classes
«interface» ISalePricingStrategy
getTotal( Sale ) : Money
PercentDiscount PricingStrategy
percentage : float
getTotal( s:Sale ) : Money
??? PricingStrategy


AbsoluteDiscount OverThreshold PricingStrategy
discount : Money threshold : Money
getTotal( s:Sale ) : Money
{
return s.getPreDiscountTotal() * percentage
}
The University of Sydney Page 18
{
pdt := s.getPreDiscountTotal() if ( pdt < threshold ) return pdt else return pdt - discount } Strategy Pattern – NextGen PoS System – Create multiple SalesePricingStrategy classes, each with a polymorphic getTotal method – Each getTotal method takes the Sale object as a parameter – Thepricingstrategyobjectcanfindthepre-discountpricefromtheSale,and they apply the discounting policy – The implementation of each getTotal method will be different – E.g., PercentDiscountPricingStrategy will discount by a percentage The University of Sydney Page 19 PoS System – Strategy POS Collaboration The University of Sydney Page 20 t = getTotal loop st = getSubtotal { t = pdt * percentage } note that the Sale s is passed to the Strategy so that it has parameter visibility to it for further collaboration s : Sale lineItems[ i ] : SalesLineItem :PercentDiscount PricingStrategy t = getTotal( s ) pdt = getPreDiscountTotal PoS System – Strategy POS Collaboration – A strategy is attached to the Sale object (context object) – The Sale object delegates some of the work to its strategy object – The message to the context and strategy objects is not required to be the same (e.g., getTotal) – TheSaleobjectpassesareferencetoitselfontothestrategyobject The University of Sydney Page 21 State Design Pattern Object Behavioural Pattern Taking control of objects from the inside A structured way to control the internal behaviour of an object The University of Sydney Page 22 State Design Pattern – Purpose/Intent – Allow an object to change its behaviour when its internal state changes – The object will appear to change its class when the state changes – Known as – ObjectsforStates – Motivating Scenario – Wecanusesubtypesofclasseswithdifferentfunctionalitytorepresent different states, such as for a TCP connection with Established, Listening, Closed as states The University of Sydney Page 23 Motivating Scenario – TCP network connection – States: Established, Listening and Closed – TCP connection responds based on its current state The University of Sydney Page 24 State Design Pattern – Applicability – Anytimeyouneedtochangebehavioursdynamically,i.e.,thestateofanobject drives its behavior and change its behavior dynamically at run-time – Therearemulti-partchecksofanobject’sstatetodetermineitsbehaviour,i.e., operations have large, multipart conditional statements that depend on the object’s state – Benefits – Removescaseorif/elsestatementsdependingonstate,andreplacesthemwith function calls; makes the state transitions explicit; permits states to be shared – Limitations – Does require that all the states have to have their own objects The University of Sydney Page 25 State Pattern – Structure state->Handle()
The University of Sydney Page 26
Context
Request()
State
Handle()
ConcreteStateA
Handle()
ConcreteStateB
Handle()

State Pattern – Participants
– Context (TCPConnection)
– Defines the interface of interest to clients
– Maintains an instance of a ConcreteState subclass that defines the current state
– State (TCPState)
– Defines an interface for encapsulating the behaviour associated with a certain state of the
Context
– ConcreteState subclasses (TCPEstablished, TCPListen, TCPClosed)
– Each subclass implements a behaviour associated with a state of the Context
The University of Sydney Page 27

State Pattern – Collaborations
– Context delegates state – specific requests to the current ConcreteState object
– A context may pass itself as an argument to the State object handling the request, so the State object access the context if necessary
– Context is the primary interface for clients
– Clients can configure a context with State objects, so its clients don’t have to deal with the
State objects directly
– Either Context or the ConcreteState subclasses can decide which state succeeds another and under what circumstances
The University of Sydney Page 28

State Pattern – Code Example
The University of Sydney Page 29

State Pattern – Code Example
The University of Sydney Page 30

State Pattern – Code Example
– What is the output of StateDemo?
The University of Sydney Page 31

State Pattern – Consequences
– Localizes state-specific behaviour for different states
– Using data values and context operations mark code maintenance difficult
– State distribution across different subclasses useful when there are many states
– Better code structure for state-specific code (better than monolithic)
– It makes state transition explicit
– State transitions as variable assignments
– State objects can protect the context from inconsistent state
– State objects can be shared
– When the state they represent is encoded entirely in their type
The University of Sydney
Page 32

State Pattern – Implementation (1)
– Defining the state transitions
– Let the state subclasses specify their successor state to make the transition (decentralized)
– Achieves flexibility – easy to modify and extend the logic
– Introduces implementation dependencies between subclasses
– Table-based state transitions
– Look-up table that maps every possible input to a succeeding state
– Easy to modify (transition data not the program code) but:
• • •
The University of Sydney
Less efficient than a functional call
Harder to understand the logic (transition criteria is less explicit) Difficult to add actions to accompany the state transitions
Page 33

State Pattern – Implementation (2)
– When to create and destroy state objects?
– Pre-create them and never destroy them
• Useful for frequent state changes (save costs of re-creating states)
• Context must keep reference to all states
– Only when they are needed and destroyed them thereafter
• States are not known at run-time and context change states frequently
The University of Sydney
Page 34

State Pattern – Implementation (3)
– Using dynamic inheritance
– Changing the object’s class at run-time is not possible in most OO
languages
– delegation-based languages allow changing the delegation target at run-time
The University of Sydney Page 35

References
– Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.
1995. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley Longman Publishing Co., Inc., Boston, MA, USA.
The University of Sydney Page 36

Task for Week 6
– Submit weekly exercise on canvas before 23.59pm Sunday
– Well organize time and continue assignment 2
– Attend Helpdesk session if you have any questions/difficulties on implementation perspective
The University of Sydney Page 37

What are we going to learn on week 7?
– Testing
– Not next week but the week after next week
– Next week is mid-break week
– no lecture and tutorials during mid-break week but Helpdesk session runs as normal at 1pm Thursday during mid-break week
The University of Sydney
Page 38