You are on page 1of 103

CSH2E3

Analisis dan Perancangan Perangkat


Lunak (APPL)
KK SIDE

Pertemuan 13
Prinsip Desain
OO – Design
Pattern

2 1/31/2019
Overview
Pattern Introduction
Design Pattern Inroduction
OO Design Problem Sampler
Design Pattern
– Creational Pattern
– Structural Pattern
– Behavioral Pattern

Difficulties and Risks


PATTERN INTRODUCTION
What is a pattern?
Patterns = problem/solution pairs in context
Patterns facilitate reuse of successful software
architectures and design
Not code reuse
– Instead, solution/strategy reuse
– Sometimes, interface reuse

5
Patterns in engineering
How do other engineers find and use patterns?
– Mature engineering disciplines have handbooks describing
successful solutions to known problems
– Automobile designers don't design cars from scratch using the
laws of physics
– Instead, they reuse standard designs with successful track
records, learning from experience
– Should software engineers make use of patterns? Why?
– “Be sure that you make everything according to the pattern I have shown you here
on the mountain.” Exodus 25:40.

Developing software from scratch is also expensive


– Patterns support reuse of software architecture and design
Design challenges
Designing software for reuse is hard. One must find:
– a good problem decomposition, and the right software
– a design with flexibility, modularity and elegance
designs often emerge from trial and error
successful designs do exist
– two designs they are almost never identical
– they exhibit some recurring characteristics
Can designs be described, codified or standardized?
– this would short circuit the trial and error phase
– produce "better" software faster

7
Why Patterns?
Design is a challenging task:
– Balancing concerns, e.g. performance, adaptability, reliability.
– Defining components and their interrelationships.
Thus experienced designers:
– Rarely start from first principles
– Look for similarities to problems solved in the past.
– Apply a working "handbook" of approaches
Patterns make expert knowledge widely available
– Supports focusing on the truly distinctive design problems.
– Aids design evaluation at higher level of abstraction
– Provides a useful working vocabulary for design

8
Levels of Patterns
Patterns occur at every level of development.
Code level: Idioms
– Recurring control structure groupings.
– Example: sentinel terminated loop.
System Level: Architectural styles
– Recurring system level structures.
– Example: layers (e.g., Internet protocols).
– Example: client/server (e.g., World Wide Web).
Subsystem Level: Design patterns
– Recurring tactical structures.
– Example: iterators to process collections of objects.
– This level is the focus of these slides.

9
DESIGN PATTERN
INTRODUCTION
What Is a Design Pattern?
A design pattern
–Is a common solution to a recurring
problem in design
–Abstracts a recurring design structure
–Comprises class and/or object
 Dependencies
 Structures
 Interactions
 Conventions
–Names & specifies the design structure explicitly
–Distils design experience
What Is a Design Pattern?
A design pattern has 4 basic parts:
1. Name
2. Problem
3. Solution
4. Consequences and trade-offs of application

Language- and implementation-independent


A “micro-architecture”
Adjunct to existing methodologies (Unified, OMT, etc.)
No mechanical application
– The solution needs to be translated into concrete terms in the
application context by the developer
Goals
Codify good design
– Distil and disseminate experience
– Aid to novices and experts alike
– Abstract how to think about design
Give design structures explicit names
– Common vocabulary
– Reduced complexity
– Greater expressiveness
Capture and preserve design information
– Articulate design decisions succinctly
– Improve documentation
Facilitate restructuring/refactoring
– Patterns are interrelated
– Additional flexibility
Gang of Four
The book that started it
all
Community refers to
authors as the “Gang of
Four”
Figures and some text
in these slides come
from book
On reserve in CS library
(3rd floor AVW)

14
Object Modeling Technique (OMT)
Used to describe patterns in GO4 book
Graphical representation of OO relationships
– Class diagrams show the static relationship between
classes
– Object diagrams represent the state of a program as
series of related objects
– Interaction diagrams illustrate execution of the program
as an interaction among related objects

15
Classes

16
Subclassing and Abstract Classes

17
Object diagrams

18
Interaction diagrams

19
Design Pattern Template (1st half)
NAME
scope purpose

Intent
short description of the pattern & its purpose
Also Known As
Any aliases this pattern is known by
Motivation
motivating scenario demonstrating pattern’s use
Applicability
circumstances in which pattern applies
Structure
graphical representation of the pattern using modified UML notation
Participants
participating classes and/or objects & their responsibilities
20
Design Pattern Template (2nd half)
NAME
scope purpose

....
Collaborations
how participants cooperate to carry out their responsibilities
Consequences
the results of application, benefits, liabilities
Implementation
pitfalls, hints, techniques, plus language-dependent issues
Sample Code
sample implementations in C++, Java, C#, Smalltalk, C, etc.
Known Uses
examples drawn from existing systems
Related Patterns
discussion of other patterns that relate to this one
21
GOF Pattern Description - 1
Intent
– What issue/problem does the pattern address?
– What is its rationale?
Also Known As = other names for pattern
Motivation
– Scenario illustrating problem and solution.
– A concrete exemplar.
Applicability
– When to choose the pattern.
– Poor designs addressed by pattern.

22
Pattern Description - 2
Structure
– Static: Class and object diagrams.
– Dynamic: Sequence diagrams.

Participants
– Classes and/or objects.
– Roles and responsibilities.

Collaborations
– Rules of participant interactions.
– Frequently these are constraints that are hard to diagram.

23
Pattern Description - 3
Consequences
– How does pattern meet its objectives?
– Tradeoff analysis – what gets better, what may get worse.
– Flexibility: what parts can vary independently?

Implementation & Sample Code


Known Uses (to show pattern generality)
Related Patterns (in case this isn’t quite right)

24
The Gang of Four Catalog Method
Pattern name and classification as key indices
Purpose classification: creational, structural, behavioral.
Scope classification: class (compile time) or object (run-
time).
Creational – when and how objects are instantiated:
– class => defer creation to subclasses
– object => defer creation to another object.
Structural – how objects are composed into larger groups:
– class => structure via inheritance.
– object => structure via composition.
Behavioral – how responsibilities are distributed:
– class => algorithms/control via inheritance.
– object => algorithms/control via object groups.

25
Design Space for GoF Patterns
how objects/classes can be combined communication
abstracting the to form larger structures between objects
object-
instantiation
process

Scope: domain over which a pattern applies


Purpose: reflects what a pattern does
26
GoF Design pattern
relationships
OO DESIGN PROBLEM
SAMPLER
OO Design Problem Sampler - 1
Problem: Dependence on specific algorithms
– Different algorithms are appropriate in different
circumstances.
– Processing the items in a list is (slightly) different from
processing items in a hash table.
– Different algorithms (e.g., sorting) are appropriate for
different data sets.
Solution: Hide details behind an interface
– Clients get the most appropriate implementation.
– Client may make the choice and pass this on.
– Service may make the choice for the client.
29
Example Pattern - 1
Iterator
– Need to process all elements of a general collection.
– Collection structures differ, thus iteration algorithms differ.
– But iteration interface is fixed.
– Each collection produces an iterator with the appropriate
algorithm tied to the fixed iterator interface.

30
OO Design Problem Sampler - 2
Problem: Overly tight coupling
– Difficult to reuse or extend classes with high
interdependence.
– Makes extension, portability, etc., much harder.
Solution: Loosen the relationship among the classes
– Develop a simpler connection protocol .
– Centralize some of the interaction in a traffic manager.

31
Example Pattern - 2
Mediator
– Have an richly connected subsystem
 Example: Widgets on account setup dialog box in Outlook.
– Changes to one component affect many other
components:
 Selecting the “authorization required” control enables the
account name & password entry textboxes.
– Create a mediator object which knows how to synchronize
the subsystem components.
– All notifications go to the mediator.
– All changes initiated by the mediator.

32
OO Design Problem Sampler - 3
Problem:
– User interfaces change often, especially on the internet where
look-and-feel is a competitive issue. Also, the same information
is presented in different ways. The core business logic and data
is stable.
Solution: Hide details behind an interface
– Use the software engineering principle of “separation of
concerns” to divide the application into three areas:
 Model encapsulates the core data and functionality
 View encapsulates the presentation of the data there can be
many views of the common data
 Controller accepts input from the user and makes request
from the model for the data to produce a new view.

33
Example Pattern - 3
MVC Architecture
The Model represents the structure of the data in the
application, as well as application-specific operations on
those data.
A View (of which there may be many) presents data in
some form to a user, in the context of some application
function.
A Controller translates user actions (mouse motions,
keystrokes, words spoken, etc.) and user input into
application function calls on the model, and selects the
appropriate View based on user preferences and Model
state.

34
Making Objects
The Smart Way

CREATIONAL PATTERNS
What are creational patterns?
Design patterns that deal with object creation
mechanisms, trying to create objects in a manner
suitable to the situation
Make a system independent of the way in which
objects are created, composed and represented
Recurring themes:
–Encapsulate knowledge about which concrete classes the
system uses (so we can change them easily later)
–Hide how instances of these classes are created and put
together (so we can change it easily later)
Benefits of creational patterns
Creational patterns let you program to an interface defined by
an abstract class
That lets you configure a system with “product” objects that
vary widely in structure and functionality
Example: GUI systems
– InterViews GUI class library
– Multiple look-and-feels
– Abstract Factories for different screen components
Benefits of creational patterns
Generic instantiation – Objects are instantiated without having
to identify a specific class type in client code (Abstract Factory,
Factory)
Simplicity – Make instantiation easier: callers do not have to
write long complex code to instantiate and set up an object
(Builder, Prototype pattern)
Creation constraints – Creational patterns can put bounds on
who can create objects, how they are created, and when they
are created
Creational Patterns
Abstract Factory:
– Factory for building related objects

Builder:
– Factory for building complex objects incrementally

Factory Method:
– Method in a derived class creates associates

Prototype:
– Factory for cloning new instances from a prototype

Singleton:
– Factory for a singular (sole) instance
Pattern: Singleton
Name: Singleton
Problem:
How can we guarantee that one and only one
instance of a class can be created?
Context: In some applications it is important
to have exactly one instance of a class, e.g. sales of
one company.
Forces: Can make an object globally accessible as a
global variable, but this violates encapsulation.
Could use class (static) operations and attributes, but
polymorphic redefinition is not always possible.

Solution:
Create a class with a class operation getInstance().
When class is first accessed, this creates relevant
object instance and returns object identity to client.
On subsequent calls of getInstance(), no new
instance is created, but identity of existing object is
returned.
Singleton Design Purpose

Ensure that there is exactly one instance of a


class S. Be able to obtain the instance from
anywhere in the application.

Design Pattern Summary


Make the constructor of S private; define a
private static attribute for S of type S; define a
public accessor for it.
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
The Singleton Interface for Clients

User mainUser = User.getTheUser();


Singleton: Class Model
Client

Singleton Design Pattern

MyClass singletonOfMyClass
getSingletonOfMyClass(): MyClass
«static»
1

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Singleton Structure
Singleton Object identifier for singleton
instance, class scope or static
-uniqueInstance
-singletonData Returns object identifier for
+getInstance( ) unique instance, class-scope
+getSingletonData( ) or static
+singletonOperation( ) Private constructor only accessible
-Singleton( ) via getInstance()

getInstance( ) {
if ( uniqueInstance == null )
{ uniqueInstance = new Singleton( ) }
return uniqueInstance
}
The Singleton Design Pattern -- applied to MyClass
1. Define a private static member variable of
MyClass of type MyClass
private static MyClass singletonOfMyClass = new MyClass();
2. Make the constructor of MyClass private
private MyClass() { /* …. constructor code …. */ };
3. Define a public static method to access the
member
public static MyClass getSingletonOfMyClass()
{
return singletonOfMyClass;
}
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Application of Singleton
to Experiment Example

Experiment
theExperiment: Experiment
theExperiment
Client analyze()
getTheExperiment(): Experiment «static»
reportResults()
1

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Key Concept:  Singleton Design Pattern 
When a class must have exactly one instance,
make the constructor private and the instance
a private static variable with a public accessor.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Example Code

public class Runtime


{
private static Runtime currentRuntime = new Runtime();

// Returns the runtime object associated with the current


// Java application.

public static Runtime getRuntime()


{
return currentRuntime;
}

private Runtime() { }

}
Comments
• To specify a class has only one instance, we make
it inherit from Singleton.
+ controlled access to single object instance through
Singleton encapsulation
+ Can tailor for any finite number of instances
+ namespace not extended by global variables
- access requires additional message passing
- Pattern limits flexibility, significant redesign if
singleton class later gets many instances
Abstract Factory: An Example
PIM system
Manage addresses and phone numbers
– You hard-coded it for US data
– At some point, you wanted to extend it to incorporate any address /
phone number
– So you subclassed
 DutchAddress, JapanesePhoneNumber, etc.
– But now, how do you create them?
Abstract Factory: Overview
Intent
–Provide an interface for creating families of related or
dependent objects without specifying their concrete classes
Analogous to a pasta maker
Your code is the pasta maker
Different disks create different pasta shapes:
these are the factories
All disks have certain properties in common
so that they will work with the pasta maker
All pastas have certain characteristics in
common that are inherited from the generic
“Pasta” object
Abstract Factory: Participants
AbstractFactory
Declares an interface for operations
that create abstract products
ConcreteFactory
Implements the operations to create
concrete product objects: usually
instantiated as a Singleton
AbstractProduct
Declares an interface for a type of
product object; Concrete Factories
produce the concrete products
ConcreteProduct
Defines a product object to be
created by the corresponding
concrete factory
Abstract Factory: Applicability
Use Abstract Factory when:
– A system should be independent of how its products are created,
composed, and represented
– A system should be configured with one of multiple families of products
– You want to provide a class library of products, and you want to reveal
just their interfaces, not their implementations
Abstract Factory: Consequences
Good:
–Isolates concrete classes
 All manipulation on client-side done through abstract interfaces
–Makes exchanging product families easy
 Just change the ConcreteFactory
–Enforces consistency among products
Bad
–Supporting new kinds of products is difficult
–Have to reprogram Abstract Factory and all subclasses
–But it’s not so bad in dynamically typed languages
Abstract Factory: Implementation
Usually should be a Singleton
Define a Factory Method (GoF) in AbstractFactory –
ConcreteFactory then specifies its products by overriding the
factory for each
public class USAddressFactory implements AddressFactory{
public Address createAddress(){
return new USAddress();
}
public PhoneNumber createPhoneNumber(){
return new USPhoneNumber();
}
}
Maybe use Prototype pattern in dynamically typed languages
(e.g. Smalltalk) to simplify creation
STRUCTURAL PATTERN
Structural patterns
Describe ways to assemble objects to realize new
functionality
– Added flexibility inherent in object composition due to
ability to change composition at run-time
– not possible with static class composition

Example: Proxy
– Proxy: acts as convenient surrogate or placeholder for
another object.
 Remote Proxy: local representative for object in a
different address space
 Virtual Proxy: represent large object that should be
loaded on demand
 Protected Proxy: protect access to the original object
Structural Patterns
Adapter:
– Translator adapts a server interface for a client
Bridge:
– Abstraction for binding one of many implementations
Composite:
– Structure for building recursive aggregations
Decorator:
– Decorator extends an object transparently
Facade:
– Simplifies the interface for a subsystem
Flyweight:
– Many fine-grained objects shared efficiently.
Proxy:
– One object approximates another
Pattern: Façade
Name: Façade
Problem:
How can we access a large number of classes
with a complex internal interaction in a simple
but safe way?
Solution: Introduce a dedicated interface class
that simplifies the view of the class collection.
Facade (Structure)
Facade
subsystem classes
<<façade>> Pattern Name
SecurityManager
+addAccessRight()
+addActor()
+addActorRole()
+removeActor()

AccessRight ActorRole
+addAccessRight() +addActorRole()

Actor
+addActor()
+removeActor() Method not in Facade
+changeSalary()
Comments
• Clients communicate with the subsystem by
sending requests to Façade which forwards
them to the appropriate subsystem object(s).
• Although subsystem objects perform actual
work, Façade may have to translate its
interface to subsystem interfaces.
• Clients that use the Façade don’t have to
access its subsystem objects directly.
• Usually only one Façade object is
required. Thus a Façade object is often a
singleton.
• Factory pattern can be used with Façade
to provide an interface for creating
subsystem objects in a subsystem
independent way.
• Factory can also be used as an alternative
to Façade to hide platform-specific classes.
• Mediator pattern is similar to Façade in
abstracting functionality of classes.
Decorator Design Purpose

Add responsibilities to an object at runtime.

Design Pattern Summary


Provide for a linked list of objects,
each encapsulating responsibility.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Decorator Class Model

Component 1
Client add( Component )
doAction()

Substance Decoration
doAction() doAction() objDecorated

Undecorated void doAction()


class { ….. // do actions special to this decoration
objDecorated.doAction(); // pass along
}
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
client:Client Linked
Objects in
decoration1:Decoration Decorator

decoration1.objectDecorated:Decoration

… :Decoration

….:Substance
This list is created backwards
so that the last decoration
added is the first one to be
executed
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Sequence Diagram for Decorator

:Client decoration1 Decoration1.objDecorated :Substance


:Decoration :Decoration

doAction()
doAction()

doAction()

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Decorator Applied to
Customer / Accounts AttemptToAddBadBankingComponentException
Example
<<interface>> Means exactly
BankingComponent 1 one aggregate
Client add( Component ) per account
describe()

nextComponent
Setup Customer Account
main() describe() describe()

CheckAccount SavingsAccount CDAccount


describe() describe() describe()
getLastCheckNum(): int getInterestRate(): int getDuration(): int

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Decorator Applied to Construction Example
construction

ConstructionComponent1
Client add( Component )
showPrice()

nextComponent
Setup ConstrJob ConstrMaterial
add() showPrice()
showPrice()

Window Door Beam


showPrice() showPrice() showPrice()
… … …

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Use of Decorator in java.io Reader
1

InputStream InputStreamReader BufferedReader

BufferedReader bufReader = new BufferedReader


(new InputStreamReader(System.in) );

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Key Concept:  Decorator Design Pattern 

-- allows addition to and removal from objects


at runtime
-- represents an object version of a linked list
where a client does not need to know about the
subclasses in the list
-- emphasizes the structural properties of the
substance in the list

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
BEHAVIORAL PATTERN
Behavioral Patterns
Chain of Responsibility:
– Request delegated to the responsible service provider
Command:
– Request or Action is first-class object, hence re-storable
Iterator:
– Aggregate and access elements sequentially
Interpreter:
– Language interpreter for a small grammar
Mediator:
– Coordinates interactions between its associates
Memento:
– Snapshot captures and restores object states privately
Behavioral Patterns (cont.)
Observer:
– Dependents update automatically when subject changes
State:
– Object whose behavior depends on its state
Strategy:
– Abstraction for selecting one of many algorithms
Template Method:
– Algorithm with some steps supplied by a derived class
Visitor:
– Operations applied to elements of a heterogeneous
object structure
Pattern: Observer (Behavioral)
Name: Observer
Problem: Define a one-to-many dependency
among objects so that when one object
changes state, all of its dependents are
notified and updated automatically.
Solution: MVC, but refined by separating
abstract from concrete subjects and observers
*
Subject Observer
attach(Observer) Update()
detach(Observer)
notify() for all o in
observers {
o.update( ) }

ConcreteObserver
ConcreteSubject *
observerState
subjectState() update()
getState()
setState()
return observerState =
subjectState subject.getState( )
aConcrete aConcrete aConcrete
Subject: Subject: Subject:

setState( )

notify( )

update( )

getState( )

update( )
getState( )
• ConcreteSubject notifies its observers
whenever a change occurs that could make
its observers state inconsistent with its own
• After being informed of change, a
ConcreteObserver queries the subject to
reconcile its state with subjects.
• Observer object that initiates change
request postpones its update until it gets
notification from subject. Notify() is not
always called by subject. Can be called by
an observer, or any other object.
• Pattern is well known, has wide range of
variants
Iterator
Design Purpose (Gamma et al)

Provide a way to access the elements of an


aggregate object sequentially without
exposing its underlying representation.

Design Pattern Summary


Encapsulate the iteration in a class pointing
(in effect) to an element of the aggregate.
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Purpose of Iterator
 - given a collection of objects
e.g.,
o the videos in a video store Aggregate
object
o a directory

 - having specified ways to progress through them


e.g.,
o “list in alphabetical order” iterator2
o “list all videos currently on loan” iterator7
 ... encapsulate each of these ways

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Iterator Class Model

Client

Iterator
setToFirst()
increment() Aggregate
isDone()
getCurrentItem()

ConcreteIterator 1…n ConcreteAggregate


AggregatedElement 1

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Using Iterator Functions

/*

To perform desiredOperation() on elements of


the aggregate according to the iteration (order) i:

*/

for( i.setToFirst(); !i.isDone(); i.increment() )

desiredOperation( i.getCurrentElement() );

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Functions for Iterator

// Iterator "points" to first element:


void setToFirst();
// true if iterator "points" past the last element:
boolean isDone();
// Causes the iterator to point to its next element:
void increment();
// Return the element pointed to by the iterator:
C getCurrentElement();
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Iterator in Arrays, Iterator Operations
Vector, and in
General Set to Increment Get current Check not
beginning element done yet

Index (integer) i i < myArray


on i=0 ++i myArray[ i ]
array myArray .length

Index (integer) j
The on myVector j < myVector
Iterator Vector j=0 ++j
.get( j ) .size()
myVector

Iterator (object) myIterator myIterator myIterator ! myIterator


myIterator .setToFirst() .increment() .getCurrent .isDone()
Element()

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Key: Intended sequence
Imagining Iterator of Element objects
element:
Element
Aggregate of
After first()
executes, iterator Element
references this objects
iterator: object.
Iterator
Before
increment()
executes, iterator
After increment() references this
executes, iterator object.
references this
object.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Iterator Example Setup Code

// Suppose that we have iterators for forward and


// backward order: we can re-use print_employees()

List employees = new List();


ForwardListIterator forward // to go from front to back
= new ForwardListIterator ( employees );
ReverseListIterator backward // to go from back to front
= new ReverseListIterator ( employees );

client.print_employees( forward ); // print from front to back


client.print_employees( backward ); // print from back to front

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
An Organizational Chart Example

Vanna Presley
vice president, 4 years

Sue Miller Sam Markham Sal Monahan


svce. mgr., 7 years svce. mgr., 5 years svce. mgr., 1 year

Inez Clapp Inky Conway Iolanthe Carp Inge Carlson


ind. contrib., 11 ind. contrib., 6 ind. contrib., 8 ind. contrib., 12

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Iterating by Years of Service Over an Organization Chart

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Design Goal At Work:  Flexibility , Correctness 
Separate the “visiting” procedure from
the processing of individual employees.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Class Structure for Client Setup
Iterator Example

OrgChartDP OrgChartIteratorDP

OrgChartIterator
Employee first()
display() next()
isDone()
currentItem()

Teller
ServiceIterator
Supervisor
OrgSeniorityIterator
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
<<interface>> Iterator in the Java API
Iterator
next() Collection
hasNext() Iterator iterator()
remove()

ListIterator List AbstractCollection

Iter *

AbstractList
ListIterator listIterator()

ListItr *
ArrayList Vector
* IBM implementation Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
<<interface>> Address Book Application using Java Iterator
Iterator
next() Collection
hasNext() Iterator iterator()
remove()

ListIterator List

AbstractList
ListItr *
ListIterator listIterator()

ArrayList

0..n
NameAddressEntry AddressBook
* IBM implementation Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Key Concept:  Iterator Design Pattern 
-- to access the elements of a collection.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
DIFFICULTIES AND RISKS
Difficulties and Risks When Creating
Class Diagrams
Patterns are not a panacea:
– Whenever you see an indication that a pattern should be
applied, you might be tempted to blindly apply the
pattern.
– This can lead to unwise design decisions .

Resolution:
– Always understand in depth the forces that need to be
balanced, and when other patterns better balance the
forces.
– Make sure you justify each design decision carefully.

96
Principles Underlying Patterns
Rely on abstract classes to hide differences
between subclasses from clients
– object class vs. object type
 class defines how an object is implemented
 type defines an object’s interface (protocol)

Program to an interface, not an implementation

97
Principles (cont’d)
Black-box vs. white-box reuse
– black-box relies on object references, usually through
instance variables
– white-box reuse by inheritance
– black-box reuse preferred for information hiding, run-time
flexibility, elimination of implementation dependencies
– disadvantages: Run-time efficiency (high number of
instances, and communication by message passing)

Favor composition over class inheritance

98
Principles (cont’d)
Delegation
– powerful technique when coupled with black-box reuse
– Allow delegation to different instances at run-time, as long
as instances respond to similar messages
– disadvantages:
 sometimes code harder to read and understand
 efficiency (because of black-box reuse)

99
Difficulties and Risks When Creating
Class Diagrams
Developing patterns is hard
– Writing a good pattern takes considerable work.
– A poor pattern can be hard to apply correctly

Resolution:
– Do not write patterns for others to use until you have
considerable experience both in software design and in the
use of patterns.
– Take an in-depth course on patterns.
– Iteratively refine your patterns, and have them peer
reviewed at each iteration.

100
Ref
THANK YOU