Materi 15. Design Pattern - compressed-SWD
Materi 15. Design Pattern - compressed-SWD
Materi 15. Design Pattern - compressed-SWD
Design Pattern
1 2/10/23
Overview
Pattern Introduction
Design Pattern Inroduction
OO Design Problem Sampler
Design Pattern
– Creational Pattern
– Structural Pattern
– Behavioral Pattern
4
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.
6
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
7
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.
8
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
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
this book
It has 23 patterns
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
14
Classes
15
Subclassing and Abstract Classes
16
Object diagrams
17
Interaction diagrams
time
18
GOF Pattern Description – 1/3
Name
– The design pattern name
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.
19
Pattern Description – 2/3
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.
20
Pattern Description – 3/3
Consequences
– How does pattern meet its objectives?
– Tradeoff analysis – what gets better, what may get worse.
– Flexibility: what parts can vary independently?
21
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.
22
Design Space for GoF Patterns
how objects/classes can be combined communication
abstracting the to form larger structures between objects
object-
instantiation
process
26
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.
27
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.
28
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.
29
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.
30
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.
31
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
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
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
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.
50
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)
51
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)
52
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)
53
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.
54
References
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.
The Singleton Interface for Clients
MyClass singletonOfMyClass
getSingletonOfMyClass(): MyClass
«static»
1
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Singleton Singleton Object identifier for singleton
instance, class scope or static
Structure -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
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();
private Runtime() { }
}
Comments
+addAccessRight()
+addActor()
+addActorRole()
+removeActor()
AccessRight
+addAccessRight() ActorRole
+addActorRole()
Actor
+addActor()
+removeActor()
+changeSalary() Method not in Facade
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
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Decorator Component 1
Class Client add( Component )
Model
doAction()
Substance Decoration
doAction() doAction() objDecorated
decoration1.objectDecorated:Decoration
doAction()
doAction()
doAction()
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
AttemptToAddBadBankingComponentException
nextComponent
Setup Customer Account
main() describe() describe()
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
construction
Decorator
Applied to ConstructionComponent 1
Construction Client add( Component )
Example showPrice()
nextComponent
Setup ConstrJob ConstrMaterial
add() 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
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Key Concept: à Decorator Design Pattern ß
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Observer
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.
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Client
Iterator Class Model
Iterator
setToFirst()
increment() Aggregate
isDone()
getCurrentItem()
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Using Iterator Functions
/*
*/
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
Iterator Operations
Arrays,
Vector, and
Set to Get current Check not
in General beginning Increment element done yet
Index (integer) j
The on myVector j < myVector
Iterator Vector j=0 ++j
.get( j ) .size()
myVector
Aggregate of Element
After first() executes,
iterator references objects
this object.
iterator:
Iterator
Before increment()
executes, iterator
references this
After increment() object.
executes, iterator
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()
Vanna Presley
vice president, 4 years
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 ß
Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.
Client Setup
Class Structure
for Iterator OrgChartDP OrgChartIteratorDP
Example
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
Iterator in the Java API
next() Collection
hasNext() Iterator iterator()
remove()
Iter *
AbstractList
ListIterator listIterator()
ListItr *
ArrayList Vector
* IBM implementation
<<interface>>
Address Iterator
next()
Book Collection
hasNext() Iterator iterator()
Application remove()
using Java
Iterator
List
ListIterator
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.