The University of 1
Software Design and
Copyright By PowCoder代写 加微信 powcoder
Construction 1
SOFT2201 / COMP9201
Behavioural Design Patterns
School of Computer Science
The University of 2
Copyright warning
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
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
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
Do not remove this notice.
The University of 3
Announcement
– Topics in the following weeks
– Slides with demo example will be updated to Canvas after
each lecture
Week Contents Week
7 Design Pattern: Adapter & Observer Code Review 8
10 Design Pattern: Prototype & Memento Testing 11
12 Design Pattern: Singleton, Decorator and Facade
13 Unit Review
The University of 4
– Behavioral Design Patterns
– Strategy
The University of 5
Behavioural Design
The University of 6
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 7
Design Patterns – Classification based on purpose
Scope Creational Structural Behavioural
Class Factory Method Adapter (class) Interpreter
Template Method
Object Abstract Factory
Chain of Responsibility
The University of 8
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 9
Strategy Design Pattern
Object Behavioural Pattern
Algorithm design through encapsulation
The University of 10
Motivated Scenario
– Suppose you visit a store regularly to buy necessary things
– Get the normal total price during the weekday
– Get a discount on the total price during the weekend
– Get a cashback on the total price during mid-year session
The University of 11
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
– Design for varying but related algorithms that are suitable for different contexts
• Ability to change these algorithms
– Known as
The University of 12
Strategy – Structure
ContextInterface()
Algorithm()
Algorithm()
ConcreteStrategyA
Algorithm()
ConcreteStrategyB
Algorithm()
ConcreteStrategyC
The University of 13
Strategy – Participants
– Strategy
– Declares an interface common to all supported algorithms
– Used by context to call the algorithm defined by ConcereteStrategy
– ConcereteStrategy
– Implements the algorithm using the Strategy interface
– 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 14
Revisit the Motivated Example
Client’s perspective:
The University of 15
Revisit the Motivated Example
The University of 16
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 17
One more Example (Text Viewer)
– Many algorithms for breaking a stream of text into lines
Different line breaking algorithms (strategies)
Maintain &
update the line
breaks of text
Composition perspective:
private compositor com;
public composition (compositor c) {com = c;}
public void Repair ( ) { com.compose();}
Client perspective:
composition com =
new composition(
new SimpleCompositor( ));
com.Repair( );
The University of 18
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 19
Strategy Collaboration – POS Example
:PercentDiscount
PricingStrategys : Sale
st = getSubtotal
t = getTotal
lineItems[ i ] :
SalesLineItem
t = getTotal( s )
pdt = getPreDiscountTotal
{ t = pdt * percentage }
note that the Sale s is
passed to the Strategy so
that it has parameter
visibility to it for further
collaboration
The University of 20
Strategy – Consequences
– Benefits
– Family of related algorithms (behaviors) for context to reuse
– Alternative to sub-classing
– Strategies eliminate conditional statements
– Provide choice of different implementation of the same behavior
– Drawbacks
– Clients must be aware of different strategies
– Communicate overhead between Strategy and Context
– Increased number of objects in an application
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
Motivated Scenario
– Suppose you would like to connect to a TCP network and the
TCP connection would respond based on its current state
– Established
– Listening
The University of 23
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
– We can use subtypes of classes with different functionality to represent
different states, such as for a TCP connection with Established, Listening, Closed
– Known as
– Objects for States
The University of 24
State Pattern – Structure
state->Handle()
ConcreteStateA
ConcreteStateB
The University of 25
State Pattern – Participants
– Defines the interface of interest to clients
– Maintains an instance of a ConcreteState subclass that defines the current state
– Defines an interface for encapsulating the behaviour associated with a certain
state of the Context
– ConcreteState subclasses
– Each subclass implements a behaviour associated with a state of the Context
The University of 26
Revisited the Motivating Scenario
Context State
ConcreteState
The University of 27
In Class Activity – Code Example
The University of 28
In Class Activity – Code Example
The University of 29
In Class Activity – Code Example
Question: What is the output of this application?
The University of 30
State Design Pattern
– Applicability
– Any time you need to change behaviours dynamically, i.e., the state of an object
drives its behavior and change its behavior 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 31
State Pattern – Collaborations
– Context delegates state – specific requests to the current ConcreteState
– 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 32
State Pattern – Consequences
– Localizes 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 (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:
• 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
The University of 34
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
References
– , , , and .
1995. Design Patterns: Elements of Reusable Object-Oriented Software.
Addison- Publishing Co., Inc., Boston, MA, USA.
The University of 36
Task for Week 6
– Submit weekly exercise on canvas before 23.59pm Saturday
– Well organize time for assignment 2
– JSON configuration text file (tutorial 3)
– JavaFX and GUI (tutorial 4)
The University of 37
What are we going to learn next week?
– Structural Design Pattern
– Behavioral Design Pattern
– Observer
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com