0% found this document useful (0 votes)
10 views33 pages

16 CS414 Design Patterns 5

The document discusses various design patterns in object-oriented design, specifically focusing on the Composite, Observer, State, and Strategy patterns. Each pattern is explained with its intent, structure, examples, and advantages, highlighting how they facilitate better software design and maintainability. The document provides code examples in Java to illustrate the implementation of these patterns.

Uploaded by

riftxfx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views33 pages

16 CS414 Design Patterns 5

The document discusses various design patterns in object-oriented design, specifically focusing on the Composite, Observer, State, and Strategy patterns. Each pattern is explained with its intent, structure, examples, and advantages, highlighting how they facilitate better software design and maintainability. The document provides code examples in Java to illustrate the implementation of these patterns.

Uploaded by

riftxfx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Design Patterns

CS 414 Object-oriented Design


Composite

Represent a part-whole hierarchy so that clients can treat part


and whole objects uniformly.
3

Composite Pattern

• Intent and Motivation


o Compose objects into tree structures to represent
whole-part hierarchies
o Clients treat individual objects and compositions
uniformly
• A method can be called on the objects and the
compositions.
• This is a structural pattern.
4

Composite Pattern Examples


• Java statement can be while, for, if statements, which can all
include other statements
o Operation may be “evaluate”, “pretty-print”, “syntax
highlight”, “typecheck”
• Pictures can include other pictures, and also primitive
elements like a line or rectangle
o If you stretch the outer picture, it may result in stretching
the inner pictures and primitive elements.
5

Structure

Client Component AST Statement


Operation() Operation()
Add(Component) Add(Component)
Remove(Component) Remove(Component)
GetChild(int) GetChild(int)

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

Subject maintains a list of its dependents, called observers, and


notifies them automatically of any state changes.
8

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

• When an abstraction has two aspects, one dependent on the


other, encapsulate these aspects in separate objects. That lets
you vary and reuse them independently
• When a change to one object requires changing others, and you
don’t know how many objects need to be changed
• When an object should be able to notify other objects without
making assumptions about who these objects are. Don’t want
objects tightly coupled
10

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

aConcreteSubject aConcreteObserver anotherConcreteObserver

SetState()

Notify()

Update()

getState()
Update()
GetState()
14

Java Example: A Subject

public interface Subject {


public void addObserver( Observer o );
public void removeObserver( Observer o );
}
15

IntegerDataBag Subject
import java.util.ArrayList;
import java.util.Iterator;

public class IntegerDataBag implements Subject {


private ArrayList list = new ArrayList();
private ArrayList observers = new ArrayList();
public void add( Integer i ) {
list.add( i );
notifyObservers();
}
public Iterator iterator() {
return list.iterator();
}

public Integer remove( int index ) {


if( index < list.size() ) {
Integer i =
(Integer) list.remove( index );
notifyObservers();
return i;
}
return null;
}
16

IntegerDataBag Subject (contd)


public void addObserver( Observer o ) {
observers.add( o );
}

public void removeObserver( Observer o ) {


observers.remove( o );
}

private void notifyObservers() {


// loop through and notify each observer
Iterator i = observers.iterator();
while( i.hasNext() ) {
Observer o = ( Observer ) i.next();
o.update( this );
}
}
}
17
An Observer Example

public interface Observer {


public void update( Subject o );
}

public class IntegerAdder implements Observer {


private IntegerDataBag bag;

public IntegerAdder( IntegerDataBag bag ) {


this.bag = bag;
bag.addObserver( this );
}

public void update( Subject o ) {


if( o == bag ) {
System.out.println( "The contents of the IntegerDataBag have changed."
);
int counter = 0;
Iterator i = bag.iterator();
while( i.hasNext() ) {
Integer integer = ( Integer ) i.next();
counter+=integer.intValue();
}
System.out.println( "The new sum of the integers is: " + counter );
}
}
}
18

Another Observer
public class IntegerPrinter implements Observer {

private IntegerDataBag bag;

public IntegerPrinter( IntegerDataBag bag ) {


this.bag = bag;
bag.addObserver( this );
}

public void update( Subject o ) {


if( o == bag ) {
System.out.println( "The contents of the
IntegerDataBag have changed." );
System.out.println( "The new contents of the
IntegerDataBag contains:" );
Iterator i = bag.iterator();
while( i.hasNext() ) {
System.out.println( i.next() );
}
}
}
}
19
public class Driver {
public static void main( String [] args ) {
Client Code Integer i1 = new Integer( 1 ); Integer i2 = new Integer( 2 );
Integer i3 = new Integer( 3 ); Integer i4 = new Integer( 4 );
Integer i5 = new Integer( 5 ); Integer i6 = new Integer( 6 );
Integer i7 = new Integer( 7 ); Integer i8 = new Integer( 8 );
Integer i9 = new Integer( 9 );
IntegerDataBag bag = new IntegerDataBag();
bag.add( i1 ); bag.add( i2 ); bag.add( i3 ); bag.add( i4 );
bag.add( i5 ); bag.add( i6 ); bag.add( i7 ); bag.add( i8 );

IntegerAdder adder = new IntegerAdder( bag );


IntegerPrinter printer = new IntegerPrinter( bag );

// adder and printer add themselves to the bag

System.out.println( "About to add another integer to the bag:" );


bag.add( i9 );
System.out.println("");
System.out.println("About to remove an integer from the bag:");
bag.remove( 0 );
}
}
20

Consequences

• Abstract coupling between Subject and Observer


o Not tightly coupled
o Can belong to different layers of abstraction
• Support for broadcast communication
• Unexpected updates
o Too many updates
o No details on what changed
21

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

Allows an object to alter its behavior when its internal state


changes
23

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)

• How to implement such a situation?


Examnple State Machine of a Persistent Object

Source: Larman’s book on Applying UML and Patterns


25

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()

ConcreteStateA ConcreteStateB ConcreteStateC


handle() handle() handle()

TCPState
TCPConnection
Open()
Open()
Close()
Close()
Acknowledge()
Acknowledge()

state→Open()

TCPEstablished TCPListen TCPClosed


... … …
27

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 ) }

Larman { state.rollback( this ) }


{ state.commit( this ) }
example PersistentObject
{ state.save( this ) }

oid : OID PObjectState


{
state : PObjectState
// default no-op
commit() // bodies for
commit(obj : PersistentObject) // each method
delete() 1
rollback() * delete(obj : PersistentObject) }
rollback(obj : PersistentObject)
save()
save(obj : PersistentObject)
setState(PObjectState)
...

OldDirty OldClean New OldDelete


State State State State
Product Sale
Specification
...
... commit(...) delete(...) commit(...) commit(...)
... delete(...) save(...) rollback(...)
... rollback(...)

{ // 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

Enable selecting an algorithm at runtime


30

Strategy Pattern

• Intent and motivation


o Client wants to use an algorithm, but call it in the same
way irrespective of how it is implemented.
o Strategy encapsulates each algorithm and makes them
interchangeable
• Text processing tool needs to do line breaking. Many
algorithms exist – Simple, TeX, Word, etc.
31

Structure
Context Strategy
contextOperation() algorithmOperation()

ConcreteStrategyA ConcreteStrategyB ConcreteStrategyC


algorithmOperation() algorithmOperation() algorithmOperation()

Composition Compositor
repair() compose()

compositor→compose()
SimpleCompositor TeXCompositor WordCompositor
compose() compose() compose()
32

Larman’s example
«interface»
ISalePricingStrategy

getTotal( Sale ) : Money

PercentDiscount AbsoluteDiscount ???


PricingStrategy OverThreshold PricingStrategy
PricingStrategy
percentage : float ...
discount : Money
getTotal( s:Sale ) : threshold : Money ...
Money
getTotal( s:Sale ) :
Money

{ {
return s.getPreDiscountTotal() * percentage pdt := s.getPreDiscountTotal()
} if ( pdt < threshold )
return pdt
else
return pdt - discount
}
Questions?

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy