16 CS414 Design Patterns 5
16 CS414 Design Patterns 5
Composite Pattern
Structure
Leaf
Operation()
Composite
Operation()
Assignment
Operation() … WhileStmt
Operation()
Add(Component) Add(Component)
Remove(Component) Remove(Component)
GetChild(int) GetChild(int)
6
Example
• Component: ArithmeticExpression
• Composite:
o AdditionExpression
o SubtractionExpression
o Multiplication
o Division
o Remainder…
• Leaf
o Integer Literal
o Variable
o Constant
Observer
Observer pattern
• Intent
o Defines a on-to-many dependency between objects so
that when one object changes state, all its dependents
are notified and updated automatically
• Also known as:
o Dependents, publish-subscribe
• Motivation
o Maintaining consistency between related objects
9
Applicability
Structure
Subject Observer
Attach(Observer) Update()
Detach(Observer)
for all o in observers {
Notify()
o->Update()
}
subject
ConcreteObserver
Update()
observerState
ConcreteSubject
GetState()
observerState =
SetState()
subject->GetState()
subjectState
return subjectState
11
Participants
• Subject
o Knows its observers (any number)
o Provides an interface for attaching and detaching Observer objects
• Observer
o Defined an updating interface for objects that should be notified of changes in a
subject
• ConcreteSubject
o Stores state of interest to ConcreteObserver objects
o Sends a notification to its observers when state changes
12
Participants (contd)
• ConcreteObserver
o Maintains a reference to a ConcreteSubject object
o Stores state that should stay consistent with the subject’s
o Implements the Observer updating interface to keep its state consistent with the subject’s
• Collaborations
o ConcreteSubject notifies its observers whenever a change occurs that could make the
observer’s state inconsistent with its own
o After being informed, ConcreteObserver may query the subject for information to reconcile
its state
13
Observer Pattern
Collaborations
SetState()
Notify()
Update()
getState()
Update()
GetState()
14
IntegerDataBag Subject
import java.util.ArrayList;
import java.util.Iterator;
Another Observer
public class IntegerPrinter implements Observer {
Consequences
Implementation
• Mapping subjects to their observers
• Observing more that one subject
• Who triggers the object
o State setting operations on Subject call notify
o Clients call notify
• Dangling references to deleted subjects
• Make sure Subject state is self-consistent before
notification
• Avoiding observer-specific update protocols: push and
pull models
• Specifying modifications of interest explicitly
• Encapsulating complex update semantics
State
State Pattern
• Behavior of an object changes even for the same method when the object’s
internal state changes
• Examples
o A TCP connection can have many states (e.g., Established, Listening, Closed) and can
behave differently in response to requests (open, close, connect) depending on its state.
o Objects in memory can be stored or retrieved from a persistent store. The same methods
(commit, delete, rollback, etc) behave differently depending on the state of the object
(clean, dirty, etc)
Naïve solution
• Maintain state attribute(s) inside class
• Implement methods that have conditionals based on the attribute(s)
• Can someone spot the problem(s)?
o All the methods must ensure that all the same conditions are checked
o All the methods need to be updated when a new state is added as the
software evolves
• Better solution is to
o Use polymorphism
o Localize state specific behavior to a state
26
Structure
Context State
request() handle()
state→handle()
TCPState
TCPConnection
Open()
Open()
Close()
Close()
Acknowledge()
Acknowledge()
state→Open()
Advantages
• Advantages
o All state-specific behavior is localized to one state
o Easy to add new states and transitions
• Disadvantages
o Too many classes for one particular type of object if there are multiple states
28
State and Strategy Pattern
{ state.delete( this ) }
{ // commit
PersistenceFacade.getInstance().update( obj )
obj.setState( OldCleanState.getInstance() ) }
{ // rollback
PersistenceFacade.getInstance().reload( obj )
obj.setState( OldCleanState.getInstance() ) } { // commit
PersistenceFacade.getInstance().insert( obj )
{ // delete obj.setState( OldCleanState.getInstance() ) }
obj.setState( OldDeleteState.getInstance() ) }
{ // commit
{ // save PersistenceFacade.getInstance().delete( obj )
obj.setState( OldDirtyState.getInstance() ) } obj.setState( DeletedState.getInstance() ) }
Strategy
Strategy Pattern
Structure
Context Strategy
contextOperation() algorithmOperation()
Composition Compositor
repair() compose()
compositor→compose()
SimpleCompositor TeXCompositor WordCompositor
compose() compose() compose()
32
Larman’s example
«interface»
ISalePricingStrategy
{ {
return s.getPreDiscountTotal() * percentage pdt := s.getPreDiscountTotal()
} if ( pdt < threshold )
return pdt
else
return pdt - discount
}
Questions?