计算机代考程序代写 chain flex algorithm interpreter Software Design and Construction 1 SOFT2201 / COMP9201 – cscodehelp代写

Software Design and Construction 1 SOFT2201 / COMP9201
Behavioural Design Patterns
Dr. Grane School of Computer Science
The University of 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 2

Agenda
– BehaviouralDesignPatterns – Strategy
– State
The University of 3

Behavioural Design Patterns
The University of 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 behaviour 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 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 externalise 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 parameterise 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 6

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

Strategy Design Pattern
– Purpose/Intent
– Define a family of algorithms, encapsulate each one, and make them
– –
interchangeable
– Let the algorithm vary independently from clients that use it
Known as
– Policy Motivation Scenario
– Design for varying but related algorithms that are suitable for different contexts • Ability to change these algorithms
The University of 8

Strategy – Applicability
– Many related classes differ only in their behaviour
– You need different variant of an algorithm
– An algorithm uses data that should be hidden from its clients
– A class defines many behaviours that appear as multiple statements in its operations
The University of 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 10

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

Strategy – Example (Text Viewer)
Maintain & update the line breaks of text
Client perspective:
composition com = new composition(new SimpleCompositor( )) com.Repair( );
Composition perspective:
private compositor com;
public composition (compositor c) {
com = c;}
Different line breaking algorithms (strategies)
public void Repair ( ) { com.compose();}
The University of 12

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 ConcreteStrategy object
Maintains a reference to a Strategy object
May define an interface that lets Strategy access its data
The University of 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 14

Strategy – Consequences (Benefits)
– Family of related algorithms (behaviours) for context to reuse
– Alternative to sub-classing
– Why not sub-class a Context class directly to give it different behaviours?
– Strategies eliminate conditional statements
– Provide choice of different implementation of the same behavior
The University of 15

Strategy – Consequences (Drawbacks)
– Clients must be aware of different strategies – Understandhowstrategiesdiffer
– Communicate overhead between Strategy and Context
– Strategy interface is shared by all ConcreteStrategy classes whether the
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
– Strategy objects often make good flyweight (sharing strategies)
The University of 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% of all sales during a specific period
– $10 off if the total sale is greater than $200
– Other variations
– How do we design our system to accommodate such varying pricing policies?
The University of 17

NextGen PoS – Pricing Strategy Classes
«interface» ISalePricingStrategy
getTotal( Sale ) : Money
AbsoluteDiscount OverThreshold PricingStrategy
discount : Money threshold : Money
getTotal( s:Sale ) : Money
??? PricingStrategy


PercentDiscount PricingStrategy
percentage : float
getTotal( s:Sale ) : Money
{
pdt := s.getPreDiscountTotal() if ( pdt < threshold ) return pdt else return pdt - discount } { return s.getPreDiscountTotal() * percentage } The University of 18 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 – The pricing strategy object can find the pre-discount price from the Sale, 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 19 PoS System – Strategy POS Collaboration The University of 20 s : Sale t = getTotal loop lineItems[ i ] : SalesLineItem :PercentDiscount PricingStrategy 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 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) – The Sale object passes a reference to itself on to the strategy object The University of 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 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 – The object can transition between various behaviours depending on the state – Known as – Objects for States – Motivating Scenario – We can use subtypes of classes with different functionality to represent different states, such as for a TCP connection with Established, Listening, Closed as states The University of 23 Motivating Scenario – TCP network connection – States: Established, Listening and Closed – TCP connection responds based on its current state The University of 24 State Design Pattern – Applicability – Any time you need to change behaviours dynamically, i.e., the state of an object drives its behaviour and change its behaviour dynamically at run-time – There are multi-part checks of an object’s state to determine its behaviour, i.e., operations have large, multipart conditional statements that depend on the object’s state – Benefits – Removes case or if/else statements depending on state, and replaces them with 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 25 State Pattern – Structure state->Handle()
Context
Request()
State
Handle()
ConcreteStateA
Handle()
ConcreteStateB
The University of 26
Handle()

Motivating Scenario
– TCP network connection
– States: Established, Listening and Closed
– TCP connection responds based on its current state
Context
State
handle()
The University of States
Page 27

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 28

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 29

State Pattern – Code Example
The University of 30

State Pattern – Code Example
The University of 31

State Pattern – Code Example
– What is the output of StateDemo?
The University of 32

State Pattern – Consequences
– Localises state-specific behaviour for different states
– Using data values and context operations make 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 33

State Pattern – Implementation (1)
– Defining the state transitions
– Let the state subclasses specify their successor state to make the transition (decentralised)
– 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 34
• • •
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

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 35

State Pattern – Implementation (3)
– Using dynamic inheritance
– Changingtheobject’sclassatrun-timeisnotpossibleinmostOO
languages
– delegation-basedlanguagesallowchangingthedelegationtargetat run-time
The University of 36

References
– , , , and .
1995. Design Patterns: Elements of Reusable Object-Oriented Software. Addison- Publishing Co., Inc., Boston, MA, USA.
The University of 37

Leave a Reply

Your email address will not be published. Required fields are marked *