You are on page 1of 44

Object-Oriented Software Engineering Chapter 8,

Object Design:
Reusing Pattern
Solutions
Using UML, Patterns, and Java

Object Design

♦  Object design is the process of adding details to the


requirements analysis and making implementation decisions
♦  The object designer must choose among different ways to
implement the analysis model with the goal to minimize
execution time, memory and other measures of cost.
♦  Requirements Analysis: Use cases, functional and dynamic
model deliver operations for object model
♦  Object Design: We iterate on where to put these operations in
the object model
♦  Object Design serves as the basis of implementation

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 1
Object Design: Closing the Gap
System Problem

Application objects

Requir ements gap

Solution objects

Custom objects

Object design gap

Off-the-shelf components

System design gap

Machine
Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Examples of Object Design Activities

♦  Identification of existing components


♦  Full definition of relations
♦  Full definition of classes (System Design => Service, Object
Design => API)
♦  Specifying the contract for each component
♦  Choosing algorithms and data structures
♦  Identifying possibilities of reuse
♦  Detection of solution-domain classes
♦  Optimization
♦  Increase of inheritance
♦  Decision on control
♦  Packaging

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 2
A More Detailed View of Select Subsystem

Object Design Activities


Specification Reuse

Identifying missing Identifying components


attributes & operations

Specifying visibility
Adjusting components
Specifying types &
signatures
Identifying patterns
Specifying constraints

Specifying exceptions Adjusting patterns

Check Use Cases

Restructuring Optimization

Revisiting Optimizing access


inheritance paths

Collapsing classes Caching complex


computations

Delaying complex
Realizing associations computations

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

A Little Bit of Terminology: Activities


♦  Object-Oriented Methodologies
w  System Design
t  Decomposition into subsystems
w  Object Design
t  Implementation language chosen
t  Data structures and algorithms chosen
♦  SA/SD uses different terminology:
w  Preliminary Design
t  Decomposition into subsystems
t  Data structures are chosen
w  Detailed Design
t  Algorithms are chosen
t  Data structures are refined
t  Implementation language is chosen
t  Typically in parallel with preliminary design, not separate stage

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 3
Finding Objects

♦  The hardest parts in system development:


w  Identifying objects
w  Decomposing a system into objects
♦  Requirements Analysis focuses on application domain:
w  Object identification
♦  System Design addresses both, application and implementation
domain:
w  Subsystem Identification
♦  Object Design focuses on implementation domain:
w  More object identification

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Techniques for Finding Objects

♦  Requirements Analysis
w  Start with Use Cases. Identify participating objects
w  Textual analysis of flow of events (find nouns, verbs, ...)
w  Extract application domain objects by interviewing client
(application domain knowledge)
w  Find objects by using general knowledge
♦  System Design
w  Subsystem decomposition
w  Try to identify layers and partitions
♦  Object Design
w  Find additional objects by applying implementation domain
knowledge

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 4
Application domain vs solution domain objects

♦  Application objects, also called domain objects, represent


concepts of the domain that are relevant to the system.
w  They are identified by the application domain specialists and by the
end users.
♦  Solution objects represent concepts that do not have a
counterpart in the application domain,
w  They are identified by the developers
w  Examples: Persistent data stores, user interface objects,
middleware.

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Application Domain vs Solution Domain Objects

Requirements Analysis Object Design


(Language of Application (Language of Solution Domain)
Domain)
Incident
Report
Incident
Report

Text box Menu Scrollbar

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 5
Another Source for Finding Objects : Design Patterns

♦  Observation [Gamma et al 95]:


w  Strict modeling of the real world leads to a system that reflects
today’s realities but not necessarily tomorrow’s.
♦  There is a need for reusable and flexible designs
♦  Design knowledge complements application domain
knowledge and implementation domain knowledge.
♦  What are Design Patterns?
w  A design pattern describes a problem which occurs over and over
again in our environment, and then describes the core of the
solution to that problem, in such a way that you can use this
solution a million times over, without ever doing it the same twice

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Review: Modeling Typical Aggregations


Fixed Structure: Car

* *
Doors Wheels Battery Engine

Organization Chart (variable aggregate):

University * School * Department

Dynamic tree (recursive aggregate):


Program

*
*
Block

Compound Simple
Statement Statement

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 6
Review: Modeling Typical Aggregations
Fixed Structure: Car

* *
Doors Wheels Battery Engine

Organization Chart (variable aggregate):

University * School * Department

Composite
Program
Pattern
Dynamic tree (recursive aggregate):
*
*
Block

Compound Simple
Statement Statement

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Composite Pattern
♦  Composes objects into tree structures to represent part-whole
hierarchies with arbitrary depth and width.
♦  The Composite Pattern lets client treat individual objects and
compositions of these objects uniformly

*
Client Component

Composite
Leaf
Children
Operation()
Operation() AddComponent
RemoveComponent()
GetChild()

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 7
Graphic Applications use Composite Patterns
•  The Graphic Class represents both primitives (Line,
Circle) and their containers (Picture)

*
Client Graphic

Line Circle Picture


Children
Draw()
Draw() Draw() Add(Graphic g)
RemoveGraphic)
GetChild(int)

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Modeling Software Development with Composite


Patterns

♦  Software Lifecycle:
w  Definition: The software lifecycle consists of a set of development
activities which are either other activities or collection of tasks
w  Composite: Activity (The software lifecycle consists of activities
which consist of activities, which consist of activities, which....)
w  Leaf node: Task
♦  Software System:
w  Definition: A software system consists of subsystems which are
either other subsystems or collection of classes
w  Composite: Subsystem (A software system consists of subsystems
which consists of subsystems , which consists of subsystems,
which...)
w  Leaf node: Class

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 8
Modeling the Software Lifecycle with a Composite
Pattern

Software *
Manager
Lifecycle

Task Activity
Children

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Modeling a Software System with a Composite Pattern

Software *
User
System

Class Subsystem
Children

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 9
Ideal Structure of a Subsystem: Façade, Adapter,
Bridge

♦  A subsystem consists of
w an interface object
w a set of application domain objects (entity objects)
modeling real entities or existing systems
t  Some of the application domain objects are interfaces to
existing systems
w one or more control objects
♦  Realization of Interface Object: Facade
w Provides the interface to the subsystem
♦  Interface to existing systems: Adapter or Bridge
w Provides the interface to existing system (legacy system)
w The existing system is not necessarily object-oriented!
Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Facade Pattern

♦  Provides a unified interface to a set of objects in a subsystem.


♦  A facade defines a higher-level interface that makes the
subsystem easier to use (i.e. it abstracts out the gory details)
♦  Facades allow us to provide a closed architecture

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 10
Open vs Closed Architecture
♦  Open architecture:
VIP Subsystem
w  Any client can see into the
vehicle subsystem and call on
any component or class
operation at will.
♦  Why is this good?
w  Efficiency Vehicle Subsystem
♦  Why is this bad?
w  Can’t expect the caller to Seat
understand how the subsystem
works or the complex Card
relationships within the
subsystem. AIM SA/RT
w  We can be assured that the
subsystem will be misused,
leading to non-portable code

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Realizing a Closed Architecture with a Facade


VIP Subsystem
♦  The subsystem decides exactly
how it is accessed.
♦  No need to worry about misuse
by callers
♦  If a façade is used the subsystem
can be used in an early
Vehicle Subsystem API
integration test
w  We need to write only a driver
Seat Card

AIM SA/RT

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 11
Realizing a Compiler with a Facade pattern
Compiler

Compiler

compile(s)

CodeGenerator Lexer

create() getToken()

Optimizer Parser

create() generateParseTree()

ParseNode

create()

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

UML Notation for subsystems: Package


♦  Package = Collection of classes that are grouped together
♦  Packages are often used to model subsystems
♦  Notation:
w  A box with a tab.
w  The tab contains the name of the package

Compiler Compiler
Compiler

compile(s)

CodeGenerator Lexer

create() getToken()

Optimizer Parser

create() generateParseTree()

ParseNode

create()

♦  In Together-J, every class is assigned to a default package


w  When you create a class, the class is assigned to the default package directly
containing the class diagram.
w  You can create other packages, but cannot delete the default package

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 12
Some Additional Definitions

♦  Before we go to the next pattern let’s review


the goal and some terms

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

The use of inheritance

♦  Inheritance is used to achieve two different goals


w  Description of Taxonomies
w  Interface Specification
♦  Identification of taxonomies
w  Used during requirements analysis.
w  Activity: identify application domain objects that are
hierarchically related
w  Goal: make the analysis model more understandable
♦  Service specification
w  Used during object design
w  Activity:
w  Goal: increase reusability, enhance modifiability and extensibility
♦  Inheritance is found either by specialization or generalization

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 13
Metamodel for Inheritance

♦  Inheritance is used during analysis and object design

Inheritance Object
Design
Analysis
activity

Taxonomy Inheritance
for Reuse

Inheritance detected Inheritance detected Specification Implementation


by specialization by generalization Inheritance Inheritance

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Taxonomy Example

Mammal

Tiger Wolf Wale

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 14
Reuse
♦  Main goal:
w  Reuse knowledge from previous experience to current problem
w  Reuse functionality already available
♦  Composition (also called Black Box Reuse)
w New functionality is obtained by aggregation
w The new object with more functionality is an
aggregation of existing components
♦  Inheritance (also called White-box Reuse)
w New functionality is obtained by inheritance.
♦  Three ways to get new functionality:
t  Implementation inheritance
t  Interface inheritance
t  Delegation

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Implementation Inheritance vs Interface Inheritance

♦  Implementation inheritance
w Also called class inheritance
w Goal: Extend an applications’ functionality by reusing
functionality in parent class
w Inherit from an existing class with some or all operations
already implemented

♦  Interface inheritance
w Also called subtyping
w Inherit from an abstract class with all operations
specified, but not yet implemented

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 15
Implementation Inheritance
♦  A very similar class is already implemented that does almost
the same as the desired class implementation.

❖  Example: I have a List List


Add()
class, I need a Stack Remove()
class. How about “Already
subclassing the Stack implemented”
class from the List class
and providing three Stack
Push()
methods, Push() and Pop()
Pop(), Top()? Top()

❖  Problem with implementation inheritance:


Some of the inherited operations might exhibit unwanted
behavior. What happens if the Stack user calls Remove()
instead of Pop()?
Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Delegation

♦  Delegation is a way of making composition (for example


aggregation) as powerful for reuse as inheritance
♦  In Delegation two objects are involved in handling a request
w  A receiving object delegates operations to its delegate.
w  The developer can make sure that the receiving object does not
allow the client to misuse the delegate object

calls Delegates to Delegate


Client Receiver

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 16
Delegation instead of Implementation Inheritance
♦  Inheritance: Extending a Base class by a new operation or
overwriting an operation.
♦  Delegation: Catching an operation and sending it to another object.
♦  Which of the following models is better for implementing a stack?

List
+Add() Stack List
+Remove()

Remove()
+Push() Add()
Stack +Pop()
+Top()
+Push()
+Pop()
+Top()
Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Comparison: Delegation vs Implementation Inheritance

♦  Delegation
w  Pro:
t  Flexibility: Any object can be replaced at run time by another one (as
long as it has the same type)
w  Con:
t  Inefficiency: Objects are encapsulated.
♦  Inheritance
w  Pro:
t  Straightforward to use
t  Supported by many programming languages
t  Easy to implement new functionality
w  Con:
t  Inheritance exposes a subclass to the details of its parent class
t  Any change in the parent class implementation forces the subclass to
change (which requires recompilation of both)

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 17
Design Heuristics

♦  Never use implementation inheritance, always use interface


inheritance
♦  A subclass should never hide operations implemented in a
superclass
♦  If you are tempted to use implementation inheritance, use
delegation instead

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Many design patterns use a


combination of inheritance and
delegation

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 18
Reuse...

♦  Look for existing classes in class libraries


♦  Select data structures appropriate to the algorithms
w  Container classes
w  Arrays, lists, queues, stacks, sets, trees, ...
♦  It might be necessary to define new internal classes and
operations
w  Complex operations defined in terms of lower-level operations
might need new classes and operations

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Implementation of Application Domain Classes

♦  New objects are often needed during object design:


w  The use of design patterns introduces new classes
w  The implementation of algorithms may necessitate objects to hold
values
w  New low-level operations may be needed during the decomposition
of high-level operations
♦  Example: The EraseArea() operation in a drawing program.
w  Conceptually very simple
w  Implementation
t  Area represented by pixels
t  Repair () cleans up objects partially covered by the erased area
t  Redraw() draws objects uncovered by the erasure
t  Draw() erases pixels in background color not covered by other objects

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 19
Component Selection

♦  Select existing
w  off-the-shelf class libraries
w  frameworks or
w  components
♦  Adjust the class libraries, framework or components
w  Change the API if you have the source code.
w  Use the adapter or bridge pattern if you don’t have access
♦  Architecture Driven Design

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Adapter Pattern

♦  “Convert the interface of a class into another interface clients


expect. Adapter lets classes work together that couldn’t
otherwise because of incompatible interfaces
♦  Used to provide a new interface to existing legacy components
(Interface engineering, reengineering).
♦  Also known as a wrapper
♦  Two adapter patterns:
w  Class adapter:
t  Uses multiple inheritance to adapt one interface to another
w  Object adapter:
t  Uses single inheritance and delegation
♦  Object adapters are much more frequent. We will mostly use
object adapters and call them simply adapters
Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 20
Adapter pattern
Target Adaptee
Client
Request() ExistingRequest()

adaptee

Adapter

Request()
♦  Delegation is used to
bind an Adapter and an Adaptee
♦  Interface inheritance is used to specify the interface of the
Adapter class.
♦  Target and Adaptee (usually called legacy system) pre-exist
the Adapter.
♦  Target may be realized as an interface in Java.

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Adapter pattern example


Enumeration
RegisteredServices
Client numServices();
hasMoreElements()
getService(int num);
nextElement()

adaptee

ServicesEnumeration
hasMoreElements()
public class ServicesEnumeration nextElement()
implements Enumeration {
public boolean hasMoreElements() {
return this.currentServiceIdx <= adaptee.numServices();
}
public Object nextElement() {
if (!this.hasMoreElements()) {
throw new NoSuchElementException();
}
return adaptee.getService(this.currentSerrviceIdx++);
}

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 21
Bridge Pattern

♦  Use a bridge to “decouple an abstraction from its


implementation so that the two can vary
independently”. (From [Gamma et al 1995])

♦  Also know as a Handle/Body pattern.

♦  Allows different implementations of an interface to be


decided upon dynamically.

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Using a Bridge
♦  The bridge pattern is used to provide multiple implementations
under the same interface.
♦  Examples: Interface to a component that is incomplete, not yet
known or unavailable during testing
♦  JAMES Project: if seat data is required to be read, but the seat
is not yet implemented, not yet known or only available by a
simulation, provide a bridge:

Seat imp
(in Vehicle Subsystem)
VIP SeatImplementation
GetPosition()
SetPosition()

Stub Code AIMSeat SARTSeat

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 22
Seat Implementation
public interface SeatImplementation {
public int GetPosition();
public void SetPosition(int newPosition);
}
public class Stubcode implements SeatImplementation {
public int GetPosition() {
// stub code for GetPosition
}
...
}
public class AimSeat implements SeatImplementation {
public int GetPosition() {
// actual call to the AIM simulation system
}
….
}
public class SARTSeat implements SeatImplementation {
public int GetPosition() {
// actual call to the SART seat simulator
}
...
}
Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Adapter vs Bridge

♦  Similarities:
w Both used to hide the details of the underlying
implementation.
♦  Difference:
w The adapter pattern is geared towards making unrelated
components work together
t  Applied to systems after they’re designed (reengineering,
interface engineering).
w A bridge, on the other hand, is used up-front in a design
to let abstractions and implementations vary
independently.
t  Green field engineering of an “extensible system”
t  New “beasts” can be added to the “object zoo”, even if these are
not known at analysis or system design time.

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 23
Example for Combination of Adapters and Bridges in
JAMES
Seat Seat Preferences

SetSeatPos() GetSeatPos()

Seat Impl Existing SmartCard


Adapter
Library from
Schlumberger
SLBRDR32
Bridge
SLBAPISendIsoOutT0

Seats for the Car

AIMSeat SARTSeat ActualSeat PreferencesCardlet

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

More Patterns: A Pattern Taxonomy


Pattern

Creational
Structural Pattern
Pattern
Behavioral
Pattern

Abstract Builder
Factory Pattern
Command Observer Strategy

Adapter Bridge Facade Proxy

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 24
Proxy Pattern: Motivation

♦  It is 15:00pm. I am sitting at my 14.4 baud modem connection


and retrieve a fancy web site from the US, This is prime web
time all over the US. So I am getting 10 bits/sec.
♦  What can I do?

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Proxy Pattern

♦  What is expensive?
w  Object Creation
w  Object Initialization
♦  Defer object creation and object initialization to the time you
need the object
♦  Proxy pattern:
w  Reduces the cost of accessing objects
w  Uses another object (“the proxy”) that acts as a stand-in for the real
object
w  The proxy creates the real object only if the user asks for it

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 25
Proxy pattern Subject

Request()

Proxy RealSubject
realSubject
Request() Request()

♦  Interface inheritance is used to specify the interface shared by


Proxy and RealSubject.
♦  Delegation is used to catch and forward any accesses to the
RealSubject (if desired)
♦  Proxy patterns can be used for lazy evaluation and for remote
invocation.
♦  Proxy patterns can be implemented with a Java interface.
Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Proxy Applicability

♦  Remote Proxy
w  Local representative for an object in a different address space
w  Caching of information: Good if information does not change too
often
♦  Virtual Proxy
w  Object is too expensive to create or too expensive to download
w  Proxy is a standin
♦  Protection Proxy
w  Proxy provides access control to the real object
w  Useful when different objects should have different access and
viewing rights for the same document.
w  Example: Grade information for a student shared by
administrators, teachers and students.

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 26
Virtual Proxy example Image
boundingBox()
draw()

ProxyImage RealImage
boundingBox()
realImage
boundingBox()
draw() draw()

♦  Images are stored and loaded separately from text


♦  If a RealImage is not loaded a ProxyImage displays a grey
rectangle in place of the image
♦  The client cannot tell that it is dealing with a ProxyImage
instead of a RealImage
♦  A proxy pattern can be easily combined with a Bridge

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Before

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 27
Controlling Access

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

After

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 28
Summary

♦  Composite Pattern:
w  Models trees with dynamic width and dynamic depth
♦  Adapters, Bridges, Facades, and Proxies (structural Patterns) are variations
on a single theme:
w  They reduce the coupling between two or more classes
w  They introduce an abstract class to enable future extensions
w  They encapsulate complex structures
♦  Facade Pattern:
w  Interface to a Subsystem, Closed vs Open Architecture
♦  Adapter Pattern:
w  Interface to Reality
♦  Bridge Pattern:
w  Interface Reality and Future
♦  Proxy Patterns
w  Defer object creation and initialization to the time you need the object

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

A Pattern Taxonomy
Pattern

Creational
Structural Pattern
Pattern
Behavioral
Pattern

Abstract Builder
Factory Pattern
Command Observer Strategy

Adapter Bridge Facade Proxy

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 29
Command Pattern: Motivation

♦  You want to build a user interface


♦  You want to provide menus
♦  You want to make the user interface reusable across many
applications
w  You cannot hardcode the meanings of the menus for the various
applications
w  The applications only know what has to be done when a menu is
selected.
♦  Such a menu can easily be implemented with the Command
Pattern

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Command pattern
Command
Invoker
execute()
Client

binds
Receiver
ConcreteCommand
action() execute()

♦  Client creates a ConcreteCommand and binds it with a


Receiver.
♦  Client hands the ConcreteCommand over to the Invoker
which stores it.
♦  The Invoker has the responsibility to do the command
(“execute” or “undo”).

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 30
Menu Example
Invoker:
Asks the Command object
To carry out the request

Menu *
Menu Command
Item
execute()
Application

*
binds
Document
Client Copy Paste
action() execute() execute()

Concrete
Receiver Command

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Command pattern Applicability

♦  “Encapsulate a request as an object, thereby letting you


w  parameterize clients with different requests,
w  queue or log requests, and
w  support undoable operations.”

♦  Uses:
w  Undo queues
w  Database transaction buffering

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 31
Command pattern: Editor with unlimited undos

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Structuring the objects


ConcreteCommands
Invoker (Control objects)
(Boundary objects)
UndoQueue

Menu
MoveCommand

Triangle

Editor
Rectangle

Receiver Circle
(Entity objects)
Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 32
Command pattern: typical sequence
aUser aRectangle:
anEditor moveCommand undoQueue
Rectangle
Drags mouse
newCommand(info)

“MoveCommand1”

store(MoveCommand1)

execute()

move(x, y)

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Observer pattern (293)

♦  “Define a one-to-many dependency between objects so that


when one object changes state, all its dependents are notified
and updated automatically.” (p. 293)
♦  Also called “Publish and Subscribe”

♦  Uses:
w  Maintaining consistency across redundant state
w  Optimizing batch changes to maintain consistency

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 33
Observer pattern (continued)
Observers Subject

9DesignPatterns2.ppt

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Observer pattern (continued)


Subject observers *
attach(observer) Observer
detach(observer) update()
notify()

subject
ConcreteObserver
ConcreteSubject update()
getState()
setState(newState) observerState
subjectState

♦  The Subject represents the actual state, the Observers


represent different views of the state.
♦  Observer can be implemented as a Java interface.
♦  Subject is a super class (needs to store the observers vector)
not an interface.

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 34
Sequence diagram for scenario: 
Change filename to “foo”
aFile anInfoView aListView

Attach()
Attach()

setState(“foo”)
Subject goes through all its
observers and calls update() on
notify() them, asking for the new
state is decoupled from
the notification
update()

getState()
“foo”
update()

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Animated Sequence diagram


aFile anInfoView aListView

Attach()
Attach()

setState(“foo”)

notify()

update()
update()

getState()
“foo”

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 35
Observer pattern implementation in Java

// import java.util;

public class Observable extends Object {


public void addObserver(Observer o);
public void deleteObserver(Observer o);
public boolean hasChanged();
public void notifyObservers();
public void notifyObservers(Object arg);
}

public interface Observer {


public void update(Observable o, Object arg);
}
public class Subject extends Observable{
public void setState(String filename);
public string getState();
}

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Strategy Pattern

♦  Many different algorithms exists for the same task


♦  Examples:
w  Breaking a stream of text into lines
w  Parsing a set of tokens into an abstract syntax tree
w  Sorting a list of customers
♦  The different algorithms will be appropriate at different times
w  Rapid prototyping vs delivery of final product
♦  We don’t want to support all the algorithms if we don’t need
them
♦  If we need a new algorithm, we want to add it easily without
disturbing the application using the algorithm

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 36
Strategy Pattern
Policy

Context *
Strategy
ContextInterface() AlgorithmInterface

ConcreteStrategyA ConcreteStrategyB ConcreteStrategyC

AlgorithmInterface() AlgorithmInterface() AlgorithmInterface()

Policy decides which Strategy is best given the current Context


Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Applying a Strategy Pattern in a Database Application

Database
Strategy * Strategy
Search() Sort()
Sort()

BubbleSort QuickSort ShellSort

Sort(CustomerList) Sort(CustomerList) Sort(CustomerList)

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 37
Applicability of Strategy Pattern

♦  Many related classes differ only in their behavior. Strategy


allows to configure a single class with one of many behaviors
♦  Different variants of an algorithm are needed that trade-off
space against time. All these variants can be implemented as a
class hierarchy of algorithms

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

A Pattern Taxonomy
Pattern

Creational
Structural Pattern
Pattern
Behavioral
Pattern

Abstract Builder
Factory Pattern
Command Observer Strategy

Adapter Bridge Facade Proxy

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 38
Abstract Factory Motivation

♦  Consider a user interface toolkit that supports multiple looks


and feel standards such as Motif, Windows 95 or the finder in
MacOS.
w  How can you write a single user interface and make it portable
across the different look and feel standards for these window
managers?
♦  Consider a facility management system for an intelligent house
that supports different control systems such as Siemens’
Instabus, Johnson & Control Metasys or Zumtobe’s proprietary
standard.
w  How can you write a single control system that is independent from
the manufacturer?

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Abstract Factory

AbstractFactory AbstractProductA

Client
CreateProductA
CreateProductB

ProductA1 ProductA2

ConcreteFactory1 AbstractProductB

CreateProductA
CreateProductB

ProductB1 ProductB2

ConcreteFactory2

CreateProductA Initiation Assocation:


CreateProductB Class ConcreteFactory2 initiates the
associated classes ProductB2 and ProductA2
Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 39
Applicability for Abstract Factory Pattern
♦  Independence from Initialization or Representation:
w  The system should be independent of how its products are created,
composed or represented
♦  Manufacturer Independence:
w  A system should be configured with one of multiple family of products
w  You want to provide a class library for a customer (“facility management
library”), but you don’t want to reveal what particular product you are
using.
♦  Constraints on related products
w  A family of related products is designed to be used together and you need
to enforce this constraint
♦  Cope with upcoming change:
w  You use one particular product family, but you expect that the underlying
technology is changing very soon, and new products will appear on the
market.

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Example: A Facility Management System for the Intelligent


Workplace
IntelligentWorkplace
LightBulb
Facility
Mgt InitLightSystem
System InitBlindSystem
InitACSystem
InstabusLight ZumbobelLight
Controller Controller

Blinds
SiemensFactory
InitLightSystem
InitBlindSystem
InitACSystem
InstabusBlind ZumtobelBlind
Controller Controller

ZumtobelFactory

InitLightSystem
InitBlindsystem
InitACSystem
Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 40
Builder Pattern Motivation

♦  Conversion of documents
♦  Software companies make their money by introducing new
formats, forcing users to upgrades
w  But you don’t want to upgrade your software every time there is an
update of the format for Word documents
♦  Idea: A reader for RTF format
w  Convert RTF to many text formats (EMACS, Framemaker 4.0,
Framemaker 5.0, Framemaker 5.5, HTML, SGML, WordPerfect
3.5, WordPerfect 7.0, ….)
t  Problem: The number of conversions is open-ended.
♦  Solution
w  Configure the RTF Reader with a “builder” object that specializes
in conversions to any known format and can easily be extended to
deal with any new format appearing on the market

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Builder Pattern

Director Builder
Construct() BuildPart()

For all objects in Structure {


Builder->BuildPart()
}

ConcreteBuilderB Represen-
BuildPart()
tation B
GetResult()
ConcreteBuilderA
BuildPart()
GetResult() Represen-
tation A

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 41
Example
RTFReader
Parse() TextConverter
ConvertCharacter()
ConvertFontChange
ConvertParagraph()
While (t = GetNextToken()) {
Switch t.Type {
CHAR: builder->ConvertCharacter(t.Char)
FONT: bulder->ConvertFont(t.Font)
PARA: builder->ConvertParagraph
}
}

TexConverter AsciiConverter HTMLConverter


ConvertCharacter() ConvertCharacter() ConvertCharacter()
ConvertFontChange ConvertFontChange ConvertFontChange
ConvertParagraph() ConvertParagraph() ConvertParagraph()
GetASCIIText() GetASCIIText() GetASCIIText()

TeXText AsciiText HTMLText

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

When do you use the Builder Pattern?

♦  The creation of a complex product must be independent of the


particular parts that make up the product
w  In particular, the creation process should not know about the
assembly process (how the parts are put together to make up the
product)
♦  The creation process must allow different representations for
the object that is constructed. Examples:
w  A house with one floor, 3 rooms, 2 hallways, 1 garage and three
doors.
w  A skyscraper with 50 floors, 15 offices and 5 hallways on each floor.
The office layout varies for each floor.

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 42
Abstract Factory vs Builder

♦  Abstract Factory
w  Focuses on product family
t  The products can be simple (“light bulb”) or complex
w  The abstract factory does not hide the creation process
t  The product is immediately returned
♦  Builder
w  The underlying product needs to be constructed as part of the
system but is very complex
w  The construction of the complex product changes from time to time
w  The builder patterns hides the complex creation process from the
user:
t  The product is returned after creation as a final step
♦  Abstract Factory and Builder work well together for a family of
multiple complex products

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Summary
♦  Structural Patterns
w  Focus: How objects are composed to form larger structures
w  Problems solved:
t  Realize new functionality from old functionality,
t  Provide flexibility and extensibility
♦  Behavioral Patterns
w  Focus: Algorithms and the assignment of responsibilities to objects
w  Problem solved:
t  Too tight coupling to a particular algorithm
♦  Creational Patterns
w  Focus: Creation of complex objects
w  Problems solved:
t  Hide how complex objects are created and put together

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 43
Conclusion

♦  Design patterns
w  Provide solutions to common problems.
w  Lead to extensible models and code.
w  Can be used as is or as examples of interface inheritance and
delegation.
w  Apply the same principles to structure and to behavior.

♦  Design patterns solve all your software engineering problems

Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java

Page 44

You might also like