Title: The Composite Pattern: the problem
1The Composite Pattern the problem
Compose objects into tree-like structures to
represent part-whole hierarchies and let clients
treat individual objects and compositions of
objects uniformly
- a drawing tool that lets users build complex
diagrams from simple elements - trees with
heterogeneous nodes e.g. the parse tree of a
program - a containment hierarchy for technical
equipment
2(No Transcript)
3(No Transcript)
4The Composite Pattern Participants
- Component
- declares the interface for objects in the
composition - implements default behavior for the interface
common to all objects - declares an interface for accessing and managing
child components - (optional) defines/implements an interface for
accessing a components parent - Leaf defines behavior for primitive objects in
the composition - Composite
- defines behavior for components having children
- stores child components
- implements child access and management
operations in the component interface - Client manipulates objects in the composition
through the component interface
5(No Transcript)
6(No Transcript)
7The Composite Pattern Collaboration
- Clients use the Component class interface to
interact with objects in the composition - If the recipient is a Leaf, the request is
handled directly - If the recipient is a Composite the request is
usually forwarded to child components, some
additional operations before and/or after the
forwarding can happen
8The Composite Pattern Consequences
- Makes the Client simple clients can treat
composite structures and individual objects
uniformly, clients normally dont know and should
not care whether they are dealing with a leaf or
a composite - Makes it easier to add new types of components
client code works automatically with newly
defined Composite or Leaf subclasses - - Can make a design overly general the
disadvantage of making it easy to add new
components is that it is difficult to restrict
the components of a composite, sometimes you want
a composite to have only certain types of
children, with the Composite Patterns you cannot
rely on the type system to enforce this for you,
you have to implement and use run-time checks
9The Composite Pattern Implementation (1)
- Explicit parent references simplify traversal
and management of composite structures are best
defined in the Component class it is essential
to maintain the invariant that all children of a
composite have as their parent the composite that
in turn has them as children - Sharing components can be useful for example to
reduce storage requirements but can lead to
ambiguities when requests propagate up the
structure - Maximizing the Component interface to achieve
that clients are unaware of the specific Leaf or
Composite class they are using, the Component
class should define as many common operations on
Leaf and Composite classes as possible this
conflicts with class hierarchy design that says
that a class should only implement operations
that make sense on all of its subclasses some
creativity is needed to find good default
implementations for operations (ex. children
(leaf) )
10The Composite Pattern Implementation (2)
- The child access and management operations
defining the child management interface at the
Component level gives transparency but costs
safety, clients can do meaningless things like
add to or delete from a leaf this must be
captured in a default implementation do nothing
or throw error ??? - The instance variable(s) holding the children
commonly this instance variable belongs where the
access and management operations are but when put
with the Component class a space penalty is
involved since Leafs never have children - Deleting Components in languages without garbage
collection it is best to make Composite
responsible for deleting its children an
exception is when Leaf objects are immutable and
thus can be shared
11The Composite Pattern Implementation (3)
- The datastructure for storing children a variety
of datastructures is available lists, trees,
arrays, hash tables the choice depends on
efficiency alternatively each child can be kept
in a separate instance variable all access and
management operations must then be implemented on
each Composite subclass - Child ordering when child order is an issue the
child access and management interface must be
designed carefully to manage this sequence - Caching when compositions need to be traversed
or searched frequently the Composite class can
cache traversal or search information on its
children changes to a component will require
invalidating the caches of its parent
12The Strategy Pattern The Problem
Define a family of algorithms, encapsulate each
one, and make them interchangeable. Strategy lets
the algorithm vary independently from clients
that use it Also known as policy
- Different line-breaking
- algorithms in an editor
- Different kinds of memory allocation
- algorithms for collection classes
- Different algorithms for checking
- valid input in different types
- of dialog boxes
Valid-input?
107
13(No Transcript)
14The Strategy Pattern Applicability
- Many different classes differ only in their
behavior using Strategy provides a way to
configure a class with one of many behaviors - Many different variants of an algorithm are
needed using Strategy the variants can be
implemented as a class hierarchy of algorithms - The algorithms use data that clients should not
know about using Strategy avoids exposing
complex, algorithm specific data
15(No Transcript)
16The Strategy Pattern Participants
- Strategy
- Declares an interface common to all supported
algorithms - Context uses this interface to call the algorithm
defined by a ConcreteStrategy - ConcreteStrategy subclasses
- Each subclass implements the algorithm using the
Strategy interface - Context
- Is configured with a ConcreteStrategy object
- May define an interface that lets Strategy access
its data
17The Strategy Pattern Collaborations
- A Context forwards requests from its clients to
its Strategy - Strategy and Context interact to implement the
chosen algorithm. - A Context may pass all the data required by the
algorithm to the Strategy when calling the
algorithm. - Context may pass itself as an argument to
Strategy operations so that these can call back
on the Context as required. - Clients usually create and pass a
ConcreteStrategy object to the Context
thereafter clients interact with the Context
exclusively
18The Strategy Pattern Consequences (1)
- Hierarchies of Strategy classes define a family
of algorithms or behaviors to reuse. Inheritance
can factor out common functionality of the
algorithms - Is alternative to subclassing, I.e. using a
hierarchy of Context classes to implement the
variations in behavior. The behavior is not
hard-wired in the context so the algorithm can
vary independently of the Context - Is an alternative to using conditional
statements for selecting desired behavior - Can offers a choice of implementations for the
same behavior (e.g. space and time tradeoffs)
19The Strategy Pattern Consequences (2)
- - Clients must be aware of different Strategies.
The clients must understand the difference
amongst what is offered to be able to select the
appropriate one. Therefor the pattern should only
be used when the variation in algorithm
(implementation) is relevant for the client. - - There is some communication overhead between
Strategy and Context. Strategy defines a
(general) interface. Many of the simpler
algorithms will not need all the information that
is passed. - - The number of objects in the application
increases. Sometimes this overhead can be reduced
when ConcreteStrategies can be implemented by
stateless objects that can be shared (cfr. The
flyweight pattern)
20The Strategy Pattern Implementation
- Defining the strategy and context interfaces
- Let context pass data to strategy operations
- Keeps context and strategy decoupled
- Context might pass data that strategy does not
need - Let context pass itself to strategy operations
and strategy can then request data from context - Couples context and strategy more closely
- Context must have more elaborate interface
- Strategies as template parameters
- In C templates can be used to configure a
context with a strategy - Only applicable when strategy can be selected at
compile time and does not need to change at run
time
21The Decorator Pattern the problem
- Attach additional responsibilities tot an
object dynamically instead of relying on
subclassing to extend functionality - Also known as wrapper
- Graphical embellishments
- to widgets
- Add compression and encryption
- responsibilities to streams
22(No Transcript)
23(No Transcript)
24(No Transcript)
25The Decorator Pattern Participants Collaboration
- Component defines the interface for objects that
can have responsibilities added to them
dynamically - ConcreteComponent defines an objects to which
additional responsibilities can be attached - Decorator maintains a reference to a component
object and defines an interface that conforms to
the Component's interface - ConcreteDecorator adds responsibilities to the
component - Decorator forwards requests to its Component
object. It may optionally perform additional
operations before and after forwarding the
request
26(No Transcript)
27The Decorator Pattern Consequences
- More flexible than static inheritance.
Responsibilities can be added and removed at
run-time by simply attaching/detaching them - Makes it easy to add a property twice
- Avoids feature loaded classes high up in the
hierarchy - -/ A decorator and its component are not
identical don't use decorator when identity
matters - - Results in a system with a lot of small objects
that all look alike. Can be hard to learn and
debug.
28The Decorator Pattern Implementation
- Interface conformance. A decorator object's
interface must conform to the interface of the
component it decorates - Omit the abstract Decorator class when only one
extra responsibility is needed - Keep Component class lightweight. Focus on
inerface not storing data. Definfition of data
representation should be deferred to subclasses - Changing the skin of an object versius changing
its guts (Decorator pattern versus Strategy
pattern)
29(No Transcript)
30The Abstract Factory Pattern the problem
Provide an Interface for creating families of
related or dependent objects without specifying
their concrete classes
- A GUI toolkit that supports multiple
look-and-feel standards
Also known as Kit
31(No Transcript)
32(No Transcript)
33The Abstract Factory Pattern Participants
- AbstractFactory declares an interface for
operations that create abstract product objects - ConcreteFactory implements the operations to
create concrete product objects - AbstractProduct declares an interface for a type
of product object - ConcreteProduct defines a product object to be
created by the corresponding concrete factory
implements the AbstractProduct interface - Client uses only interfaces declared by
AbstractProduct and AbstractFactory
34(No Transcript)
35The Abstract Factory Pattern Collaboration
- AbstractFactory defers creation of product
objects to its ConcreteFactory subclass - A single instance of a ConcreteFactory is created
at run-time this concrete factory creates
product objects having a particular
implementation
36The Abstract Factory Pattern Conseq. (1)
- Isolates concrete classes the AbstractFactory
encapsulates the responsibility and the process
to create product objects, it isolates clients
from implementation classes clients manipulate
instances through their abstract interfaces, the
product class names do not appear in the client
code - Makes exchanging product families easy the
ConcreteFactory class appears only once in an
application -that is, where it is instantiated-
so it is easy to replace because the abstract
factory creates an entire family of products the
whole product family changes at once
37The Abstract Factory Pattern Conseq. (2)
- Promotes consistency between products when
products in a family are designed to work
together it is important for an application to
use objects from one family only the abstract
factory pattern makes this easy to enforce - - Supporting new types of products is difficult
extending abstract factories to produce new kinds
of products is not easy because the set of
Products that can be created is fixed in the
AbstractFactory interface supporting new kinds
of products requires extending the factory
interface which involves changing the
AbstractFactory class and all its subclasses
38The Abstract Factory Pattern Implement. (1)
- Factories as singletons an application needs
only one instance of a ConcreteFactory per
product family, so it is best to implement this
as a singleton - Creating the products
- AbstractFactory only declares an interface for
creating products, it is up to the
ConcreteFactory subclasses to actually create
products - The most common way to do this is use a
factory-method for each product each concrete
factory specifies its products by overriding each
factory-method it is simple but requires a new
concrete factory for each product family even if
they differ only slightly - An alternative is to implement the concrete
factories with the prototype pattern the
concrete factory is initialised with a
prototypical instance of each product and creates
new products by cloning
39The Abstract Factory Pattern Implement. (2)
- Defining extensible factories
- a more flexible but less safe design is to
provide AbstractFactory with a single make
function that takes as a parameter (a class
identifier, a string) the kind of object to
create - is easier to realise in a dynamically typed
language than in a statically typed language
because of the return type of this make
operation - can for example be used in C only if all
product objects have a common base type or if the
product object can be safely coerced into the
type the client that requested the object
expects in the former the products returned all
have the same abstract interface and the client
will not be able to differentiate or make
assumptions about the class of the product
40The Bridge Pattern the problem
Decouple an abstraction from its
implementation so that the two can vary
independently Also kown as Handle/Body
collection
ds
- -graphic and windowing systems that need to run
over multiple platforms - -a logical collection hierarchy and an hierarchy
of data structures used for implementing them
llist
hashtable
bag
vector
seq
set
stack queue
41(No Transcript)
42(No Transcript)
43The Bridge Pattern Participants Collaboration
- Abstraction
- Defines the abstraction's interface
- Maintains a reference to an object of type
Implementor - RefinedAbstraction Extends the interface defined
by abstraction - Implementor defines the interface for
implementation classes (can be quite different
from that of the Abstraction, more primitive
operations) - ConcreteImplementor implements the Implementor
interface defining concrete implementations - Abstraction forwards client request to its
Implementor object
44(No Transcript)
45The Bridge Pattern Consequences
- Decoupling of interface (the Abstraction) and
implementation. - The implementation of an abstraction can be
configured, even at run-time. - Compile time dependencies are eliminated,
changing an implementation class does not require
recompiling the Abstraction class - Encourages layering leading to a better
structured system - Improved extensibility. Abstraction and
Implementor hierarchies can evolve independently - Implementation details are hidden from the
client and the client does not need to be
recompiled when an implementation class changes
46The Bridge Pattern Implementation
- Only one Implementor. A degenerate case. Still
useful because a change in the implementation of
a class does not affect the clients of the class - Creating the right implementation object.
- Abstraction knows about ConcreteImplementation
classes and selects one to instantiate (for
example in its constructor) - A default implementation initially and then a
switch - Delegate the decision to another object (see
Abstract Factory) - Use multiple inheritance. For example in C
public inheritance for the Abstraction hierarchy
and private inheritance for the Implementor
hierarchy. Is a static solution, not a true bridge
47The Command Pattern the problem
- Encapsulate a request as an object so that
- Clients can be parameterised with different
requests - Requests can be queued and logged
- Undo and redo operations become possible
- Also known as action, transaction
- -bind specific operations to GUI elements so that
these operations are executed when the user
clicks a button or selects an item from a menu
close window
start application
48(No Transcript)
49(No Transcript)
50(No Transcript)
51(No Transcript)
52The Command Pattern Participants
- Command declares an interface for executing an
operation - Concrete Command
- Defines a binding between a Receiver object and
an action - Implements Execute by invoking the corresponding
operation(s) on Receiver - Client creates a ConcreteCommand object and sets
its receiver - Invoker asks the command to carry out the
request - Receiver knows how to perform the operations
associated with carrying out a request
53(No Transcript)
54The Command Pattern Collaborations
- The client creates a ConcreteCommand object and
specifies its receiver - An invoker object stores the ConcreteCommand
object - The invoker object issues a request by calling
Execute on the command. When commands are
undoable ConcreteCommand stores state prior to
invoking Execute - The concreteCommand object invokes operations on
its receiver to carry out the request
55(No Transcript)
56The Command Pattern Consequences
- Command decouples the object that invokes the
operation from the one that knows how to perform
it - Commands are first-class objects, they van be
manipulated and extented like any other object - Different Commands can be assembled in a
composite command - It's easy to add new Commands
57The Command Pattern Implementation (1)
- How intelligent should a command be?
- Merely define a binding between a receiver and
the actions that carry out the request - Implement everything by itself without delegating
to a receiver - Find the receiver dynamically
- Supporting undo and redo
- Command must provide a way to revert the
execution (Unexecute of Undo operation) - ConcreteCommand class may need to store
additional state to be able to do so - The Receiver object
- The arguments to the operation(s) performed on
the receiver - Any original state of the receiver that changes
as a result of handling the request
58The Command Pattern Implementation (2)
- Supporting multiple level undo and redo
- The application needs to store a history list of
commands - Commands must be copied before they are put on
the history list when different invocations of
the same command must be distinguished from each
other - Avoid error accumulation in the undo process
- For commands that are not undoable and that don't
require arguments a C template can be used to
avoid creating a subclass for every kind of
action
59The Iterator Pattern The Problem
Provide a way to access the elements of an
aggregate object sequentially without exposing
its underlying representation
- support multiple types of traversals of
aggregate objects - provide a uniform interface for traversing
aggregate structures (polymorphic iteration)
( a b c d e)
First Next IsDone? CurrentItem
a
b
e
c
d
a b c d e
60(No Transcript)
61The Iterator Pattern Participants Collaboration
- Iterator
- Defines an interface for accessing and traversing
elements - ConcreteIterator
- Implements the iterator interface
- Keeps track of the current position in the
traversal of the aggregate - Aggregate
- Defines an interface for defining an Iterator
object - ConcreteAggregate
- Implements the iterator creation interface to
return an instance of the proper ConcreteIterator - A ConcreteIterator keeps track of the current
object in the aggregate and can compute the
succeeding object in the traversal
62(No Transcript)
63(No Transcript)
64The Iterator Pattern Consequences
- Supports variation in the traversal of an
aggregate complex aggregates can be traversed in
many ways, iterators make it easy to change the
traversal algorithm by just using a different
iterator instance - Simplifies the Aggregate interface the
Aggregate interface is not to be cluttered with
various types of traversal support - More than one traversal can be pending on the
same aggregate an iterator keeps track of its
own traversal state, therefor more than one
traversal can be in progress at the same time
65The Iterator Pattern Implementation (1)
- Who controls the iterator? An internal iterator
has full control over the complete iteration, the
clients hands an operation to perform and the
iterator applies that operation to each element
in the aggregate. With an external iterator the
client controls the iteration, i.e. the client
advances the traversal by requesting the next
element explicitly. External iterators are more
flexible (compare two collections on equality is
practically impossible with internal operators).
Internal iterators are easier to use but are
weak in languages that do not support functions
as first class objects. - Who defines the traversal algorithm? The iterator
can be responsible for the traversal algorithm in
which case it is easy to use different iteration
algorithms on the same aggregate and to use the
same algorithm on different aggregates. The
aggregate itself can be responsible for the
traversal algorithm and the iterator just stores
the state of the iteration (cursor)
66The Iterator Pattern Implementation (2)
- How robust is the iterator? A robust iterator
ensures that insertion and removals do not
interfere with traversal (and it does so without
copying the aggregate). Robust iterators can for
example be implemented by registering the
iterators with the aggregate and make the
aggregate adjust the internal state of the
iterators upon insertion or deletion of elements - Polymorphic iterators in C have a cost, they
require the iterator object to be allocated
dynamically by a factory method. Hence if there
is no need for polymorphism use concrete
iterators which can be allocated on the stack.
Polymorphic iterators have another drawback, they
must be deleted by the client code which is error
prone. The proxy pattern offers a solution here
use a stack allocated proxy for the real iterator
object, make the proxy ensure proper clean up in
its destructor so that when the proxy goes out of
scope the iterator object is deleted
67The Iterator Pattern Implementation (3)
- Iterators may have privileged access. An iterator
can be viewed as an extension of the aggregate
that created it. The iterator and the aggregate
are tightly coupled. In C they can be made
friends so that the aggregate does not have to
define operations with the sole purpose of making
the traversal efficient. Adding new traversals
becomes difficult since the aggregates interface
has to change then to let in another friend. - Null Iterators. A NullIterator is a degenerated
iterator which is helpful for handling boundery
conditions. By definition a NullIterator is
always done. NullIterators make traversing
tree-like recursive structures (like Composites)
easier. At each point in the traversal the
current node is asked for the iterator for its
children. An aggregate element returns a concrete
iterator, a leaf element a NullIterator
68The Visitor Pattern The Problem
Represents an operation to be performed on the
elements of an object structure. Visitor lets you
define a new operation without changing the
classes of the elements on which it operates
- many distinct and unrelated operations need to
be performed on objects in an object structure an
you want to avoid polluting their classes with
these operations - the classes defining the object structure rarely
change but you often want to define new
operations over the structure
69(No Transcript)
70(No Transcript)
71(No Transcript)
72The Visitor Pattern Participants (1)
- Context
- Declares a Visit operation for each class of
ConcreteElement in the object structure - The operations name and signature identified the
class that sends the Visit request - ConcreteVisitor
- Implements each operation declared by Visitor
- Each operation implements a fragment of the
algorithm for the corresponding class of object
in the object structure - Provides the context for the algorithm and stores
its state (often accumulating results during
traversal) - Element
- Defines an accept operation that takes a visitor
as an argument
73The Visitor Pattern Participants (2)
Collaborations
- ConcreteElement
- Implements an accept operation that takes a
visitor as an argument - ObjectStructure
- Can enumerate its elements
- May provide a high-level interface to allow the
visitor to visit its elements - May either be a Composite or a collection such as
a list or a set - A client that uses the visitor pattern must
create a ConcreteVisitor object and then traverse
the object structure visiting each element with
the visitor - When an element is visited, it calls the Visitor
operation that corresponds to its class. The
element supplies itself as an argument to this
operation
74(No Transcript)
75(No Transcript)
76The Visitor Pattern Consequences (1)
- Makes adding new operations easy a new
operation is defined by adding a new visitor (in
contrast, when you spread functionality over many
classes each class must be changed to define the
new operation) - Gathers related operations and separates
unrelated ones related behavior is localised in
the visitor and not spread over the classes
defining the object structure - - Adding new ConcreteElement classes is hardeach
new ConcreteElement gives rise to a new abstract
operation in Visitor and a corresponding
implementation in each ConcreteVisitor
77The Visitor Pattern Consequences (2)
- Allows visiting accross class hierarchies an
iterator can also visit the elements of an object
structure as it traverses them and calls
operations on them but all elements of the
object structure then need to have a common
parent. Visitor does not have this restriction. - Accumulating state visitor can accumulate
state as it proceeds with the traversal. Without
a visitor this state must be passed as an extra
parameter of handled in global variables - - Breaking encapsulation Visitors approach
assumes that the ConcreteElement interface is
powerful enough to allow the visitors to do their
job. As a result the pattern ofthen forces to
provide public operations that access an
elements internal state which may compromise its
encapsulation
78The Visitor Pattern Implementation
- Double Dispatch. The key to visitor is a double
dispatch the meaning of the accept operation
depends on the visitor and on the element.
Languages that support double dispatch (CLOS) can
do without this pattern. - Who is responsible for traversing the object
structure? Responsibility for traversal can be
with - The object structure
- The visitor is advisable when a particular
complex traversal is needed (for example one that
depends on the outcome of the operation),
otherwise it I not advisable because a lot of
traversal code will be duplicated in each
ConcreteVisitor for each aggregate
ConcreteElement - A separate iterator object
79The Singleton Pattern The Problem
Ensure that a class has exactly one instance and
provide a global point of access to it
- There can be only one print spooler, one file
system, one window manager in a standard
application - There is only one game board in a
monopoly game one maze in a maze-game
Monopoly Board
Monopoly Board
Monopoly Board
80The Singleton Pattern Participant Collaboration
- Participant
- Singleton
- is responsible for creating and storing its own
unique instance - defines an Instance operation that lets clients
access its unique instance - Collaboration
- the class level Instance operation will either
return or create and return the sole instance a
class level attribute will contain either a
default indicating there is no instance yet or
the sole instance
81(No Transcript)
82The Singleton Pattern Consequences
- Controlled access to sole instance because
the Singleton class encapsulates its sole
instance it can have strict control - Reduced name space is an improvement over
polluting the names space with global variables
that store sole instances - Permits refinement of operations and
representation the Singleton class may be
subclassed and the application can be configured
with an instance of the class you need at run
time - Permits a variable number of instances the
same approach can be used to control the number
of instances that can exist an operation that
grants access to the instance(s) must be provided - More flexible than using class operations only
83The Singleton Pattern Implementation
- Ensuring a unique instance
- the constructors or new operations must be
protected or overridden to avoid that other
instances are made accidentally by user code - Subclassing the Singleton class
- the main issue is installing a unique instance of
the desired subtype at run time - when all subclasses are known beforehand the
Instance operation can be a conditional and
create the right instance depending on some
parameter or explicit user input - when the subclasses are not known beforehand a
register can be used all subclasses register an
instance in it the Instance operation picks the
correct instance out of it
84The Factory Method Pattern The Problem
Define an interface for creating an object but
let subclasses decide which class to instantiate
- when frameworks or toolkits use abstract
classes to define and maintain relationships
between objects and are responsible for creating
the objects as well
Also known as Virtual constructor
85(No Transcript)
86(No Transcript)
87The Factory Method Pattern Participants and
Collaboration
- Product defines the interface of the objects the
factory method creates - ConcreteProduct implements the Product interface
- Creator
- declares the factory method, which returns an
object of type Product may define a default
implementation - may call the factory method to create Product
objects - ConcreteCreator overrides the factory method to
return an instance of ConcreteProduct - Creator relies on its subclasses to define the
factory method to return an instance of a
ConcreteProduct
88The Factory Method Pattern Consequences
- Eliminates the need to bind application
specific classes into your code - - Clients might have to subclass the Creator
class just to create a particular ConcreteProduct
object - Provides hooks for subclasses the factory
method gives subclasses a hook for providing an
extended version of an object - Connects parallel class hierarchies a clients
can use factory methods to create a parallel
class hierarchy (parallel class hierarchies
appear when objects delegate part of their
responsibilities to another class)
89(No Transcript)
90The Factory Method Pattern Impl. (1)
- Two major varieties are
- (1) the Creator class is an abstract class and
does not provide an implementation for the
factory method it declares the subclasses are
required to provide the implementation - (2) the Creator class is a concrete class and
provides a default for the implementation of the
factory method the factory method just brings
the flexibility for subclasses to create
different objects - Factory Methods can be parameterised with
something that identifies the object to create
(the body is then a conditional) overriding a
parameterised factory method makes it easy to
selectively extend or change the products that
are created - Use naming conventions that make clear that you
are using factory methods
91The Factory Method Pattern Impl. (2)
- In C
- factory methods are always virtual methods and
are often pure virtual - care must be taken to not call factory methods in
the Creators constructor because the factory
method in the ConcreteCreator wont be available
yet - this can be avoided by accessing products solely
through accessor operations that create the
product on demand the constructor initialises to
0, the accessor checks and creates the product if
it does not exist yet (lazy initialisation) - Using templates to avoid subclassing instead of
subclassing the Creator for each different
ConcreteProduct a template subclass of Creator
can be provided that is parameterised with the
Product class
92The Prototype Pattern The Problem
Specify the kinds of objects to create using a
prototypical instance and create new instances by
copying this prototype
- when an application needs the flexibility to be
able to specify the classes to instantiate at run
time - when instance of a class have only very
few different combinations of state
93(No Transcript)
94(No Transcript)
95The Prototype Pattern Participants an
Collaborations
- Prototype declares an interface for cloning
itself - Concrete Prototype implements an operation for
cloning itself - Client creates a new object by asking the
prototype to clone itself - Client asks a Prototype to clone itself
96The Prototype Pattern Consequences (1)
- Hides the concrete product classes from the
client clients can work with application
specific classes without modification - Products can be added and removed at run-time
new concrete products can be incorporated by just
registering them with the client - Specifying new objects by varying values new
kinds of objects are effectively defined by
instantiating a specific class, filling in some
of the instance variables and registering this as
a prototype - Specifying new objects by varying structure
complex user-defined structures can be registered
as prototypes as well and used over and over
again by cloning them
97The Prototype Pattern Consequences (2)
- Reduced subclassing as opposed to the Factory
Method pattern that often produces a hierarchy of
creator classes that mirrors the hierarchy of
ConcreteProducts - Configuring an application with classes
dynamically when the run-time environment
supports dynamic loading of classes the prototype
pattern is a key to exploiting these facilities
in static languages (the constructors of the
dynamically loaded classes cannot be addressed
statically, instead the run-time environment
creates automatically a prototype instance that
the application can use through a prototype
manager) - - Implementing the Clone operation is difficult
when the classes under consideration already
exist or when the internals include objects that
do not support copying or have circular references
98The Prototype Pattern Implementation (1)
- Using a prototype manager when the number of
prototypes in a system is not fixed it is best to
use a registry of available prototypes - Implementing the clone operation many languages
have some support for implementing the clone
operator (copy constructors in C, copy method
in Smalltalk, save load in systems that support
these) but in itself they do not solve the
shallow / deep copy issue - Initialising clones some clients are happy with
the clone as it is, others will want to
initialise the clone passing parameters to the
clone operation precludes a uniform cloning
interface either use state changing operation
that are provided on the clone immediately after
cloning or provide a Initialise method - In languages that treat classes as first class
objects the class object itself is like a
prototype for creating instances of each class
99The Builder Pattern The Problem
Separate the construction of a complex object
from its representation so that the same
construction process can create different
representations
- a RTF reader that can convert into many
different formats - a parser that produces a
complex parse tree
Title Hello you!
Title Hello you!
Save-as command of Word
ltBgtltFONT FACE"Arial" SIZE6gtltPgtTitlelt/Pgt lt/Bgtlt/
FONTgtltFONT FACE"Times"gt lt/FONTgtltIgtltFONT
FACE"Arial"gtltPgtHello you!lt/Pgtlt/Igtlt/FONTgtlt/BODYgt lt
/HTMLgt
100(No Transcript)
101The Builder Pattern Participants
- Builder specifies an abstract interface for
creating parts of a Product - ConcreteBuilder
- constructs and assembles parts of the Product by
implementing the Builder interface - defines and keeps track of the representation it
creates - provides an interface for retrieving the product
- Director constructs an object using the Builder
interface - Product
- Represents the complex object under construction
- Includes classes that define the constituent
parts including the interfaces for assembling the
parts into the final result
102(No Transcript)
103The Builder Pattern Collaboration
- The client creates the Director object and
configures it with the desired Builder object - Director notifies the builder whenever a part of
the product should be built - Builder handles requests from the director and
adds parts to the product - The client retrieves the product from the builder
104(No Transcript)
105The Builder Pattern Consequences
- Lets you vary the products internal
representation the directors uses the abstract
interface provided by the builder for
constructing the product to change the products
representation, just make a new type of builder - Allows reuse of the ConcreteBuilders all code
for construction and representation is
encapsulated different directors can use the
same ConcreteBuilders - Gives finer control over the construction
process in other creational patterns,
construction is often in one shot here the
product is constructed step by step under the
directors guidance giving fine control over the
internal structure of the resulting product
106The Builder Pattern Implementation
- Assembly and construction interfaces
- The Builder interface must be general enough to
allow the construction of products for all kinds
of ConcreteBuilders - The model for construction and assembly is a key
design issue - Why no abstract class for products?
- In the common case, the products can differ so
greatly in their representation that little is to
gain from giving different products a common
parent class - Because the client configures the Director with
the appropriate ConcreteBuilder, the client knows
the resulting products - Empty methods as default in Builder
- In C the build methods are intentionally not
pure virtual member functions but empty methods
instead this allows clients to overwrite only
the operations they are interested in
107The Facade Pattern The Problem
Provide a unified higher level interface to a set
of interfaces in a subsystem to make the
subsystem easier to use
- provide a simple interface to a complex
subsystem - decouple a subsystem from clients and other
subsystems - create layered subsystems by providing an
interface to each subsystem level
Client classes
facade
Subsystem classes
108(No Transcript)
109(No Transcript)
110The Facade Pattern Participants Collaboration
- Facade
- Knows which subsystem classes are responsible for
a request - Delegates clients requests to appropriate
subsystem objects - Subsystems Classes
- Implement the subsystem functionality
- Handle work assigned by the Facade object
- Have no knowledge of the Facade object i.e. keep
no reference to it - Clients send their request to Facade which will
then forward them to the appropriate subsystem
object
111(No Transcript)
112The Facade Pattern Consequences
- Shields clients from subsystem components
thereby reducing the number of objects that
clients deal with thus making the subsystem
easier to use - Promotes weak coupling between the subsystem
and its clients allowing components of the
subsystem to change without affecting the clients
- Reduces compilation dependencies in large
software systems - Does not prevent applications from using
subsystem classes if they need to
113The Facade Pattern Implementation
- The coupling between clients and subsystems can
be reduced even further - by making Facade an abstract class with concrete
subclasses for different implementations of a
subsystem this abstract coupling keeps clients
from knowing which implementation of a subsystem
it is they use - by configuring a Facade object with different
subsystem objects to customise simply replace
one or more of the subsystem objects - Public versus Private subsystem classes the
façade is a part of the public interface of a
subsystem together with the subsystem classes
some clients have to access directly (very few OO
languages support the notion of private subsystem
classes although it would be a very useful
feature)
114The Proxy Pattern The Problem
Provide a surrogate or placeholder for another
object to control access to it
- a remote proxy provides a local representative
for an object in a different address space - a virtual proxy creates expensive objects on
demand - a protection proxy controls access to the
original object and are useful when objects have
different access rights - a smart reference is a replacement for a bare
pointer that performs additional actions when an
object is accessed e.g. counting references,
loading a persistent object when it is first
referenced, locking the real object, ...
Client class
proxy
Real class
115(No Transcript)
116(No Transcript)
117The Proxy Pattern Participants (1)
- Proxy
- Maintains a reference that lets the proxy access
the real subject - Provides an interface identical to the Subjects
so that a proxy can be substituted for the real
subject - Controls access to the real subject and may be
responsible for creating and deleting it - Remote proxies are responsible for encoding a
request and its arguments and for sending the
request to the real subject in the other address
space - Virtual proxies may cache information about the
real subject so that they can postpone accessing
it - Protection proxies check that the caller has the
access permission to perform a request
118(No Transcript)
119The Proxy Pattern Participants (2) Collaboration
- Subject
- Defines a common interface for Realsubject and
Proxy so that a Proxy can be used anywhere a
Realsubject is expected - Realsubject
- Defines the real object that the proxy represents
- Proxy forwards the request to Realsubject when
appropriate (depends on the type of proxy)
120(No Transcript)
121The Proxy Pattern Consequences
- The Proxy pattern introduces a level of
indirection when accessing an object. This
indirection has many uses - A remote proxy can hide the fact that the object
resides in a different address space - A virtual proxy can perform optimisations
- Both protection proxies and smart pointers allow
additional housekeeping - The proxy patterns can be used to implement
copy-on-write to avoid unnecessary copying of
large objects the real subject is referenced
counted each copy requests increments this
counter but only when a clients requests an
operation that modifies the subject the proxy
actually copies it
122The Flyweight Pattern The Problem
Some applications benefit from using objects in
their design but a naïve implementation is
prohibitively expensive because of the large
number of objects
- use an object for each character in a text
document editor - use a layout object for each widget in a GUI
Column
Character
h
a
l
o
l
Row
123(No Transcript)
124(No Transcript)
125(No Transcript)
126(No Transcript)
127The Flyweight Pattern Applicability
- Apply flyweight when ALL of the following are
true - An application uses a large number of objects
- Storage cost is high because of the quantity of
objects - Most object state can be made extrinsic
- Many groups of objects can be replaced by
relatively few shared objects once extrinsic
state is removed - The application does not depend on object
identity
A
A
A
128The Flyweight Pattern Participants (1)
- Flyweight
- Declares an interface through which flyweights
can receive and act upon extrinsic state - Concrete Flyweight
- Implements the flyweight interface and adds
storage for intrinsic state - A concrete flyweight object must be sharable,
i.e. all state must be intrinsic - Unshared Concrete Flyweight
- Not all flyweights subclasses need to be shared,
unshared concrete flyweight objects have concrete
flyweight objects at some level in the flyweight
object structure
129The Flyweight Pattern Participants (2)
- Flyweight Factory
- Creates and manages flyweight objects
- Ensures that flyweights are shared properly when
a client requests a flyweight the flyweight
factory supplies an existing one from the pool or
creates one and adds it to the pool - Client
- Maintains a reference to flyweight(s)
- Computes or stores the extrinsic state of
flyweight(s)
130(No Transcript)
131The Flyweight Pattern Collaborations
- State that a flyweight needs to function must be
characterised as either intrinsic or extrinsic.
Intrinsic state is stored in the concrete
flyweight object extrinsic state is stored or
computed by client objects. Clients pass this
state to the flyweight when invoking operations. - Clients should not instantiate concrete
flyweights directly. Clients must obtain concrete
flyweight objects exclusively from the flyweight
factory object to enshure that they are shared
properly
132(No Transcript)
133The Flyweight Pattern Consequences
- - Flyweights may introduce run-time costs
associated with transferring, finding, and/or
computing extrinsic state - The increase in run-time cost are offset by
storage savings which increase - as more flyweights are shared
- as the amount of intrinsic state is considerable
- as the amount of extrinsic state is considerable
but can be computed - - The flyweight pattern is often combined with
the composite pattern to build a graph with
shared leaf nodes. Because of the sharing, leaf
nodes cannot store their parent which has a major
impact on how the objects in the hierarchy
communicate
134The Flyweight Pattern Implementation
- Removing extrinsic state
- Identify extrinsic state and remove it from the
shared objects - Removing extrinsic state will not help if there
are as many different kinds of extrinsic state as
there are objects before sharing - Ideally extrinsic state can be computed from a
separate object structure with far smaller
storage requirements - Managing shared objects
- Use an associative store with the flyweight
factory to let clients locate a particular
flyweight - Some form of reference counting or garbage
collection is needed to reclaim a flyweights
storage when it is no longer needed - When the number of flyweights is small and fixed,
consider to initialise the pool and keep the
flyweights around permanently
135The State Pattern The Problem
Allow an object to change its behavior when its
internal state changes. The object will appear to
have changed its class.
- Objects implementing connection
- protocols will react differently to the
- same message depending on whether
- the connection is established or not
- An interactive drawing program reacts
- differently on a mouse click depending
- on the tool that is picked up from the
- palette (draw-line, draw-circle, edit-text)
open
TCP Connection (established)
TCP Connection (listening)
TCP Connection (closed)
136(No Transcript)
137(No Transcript)
138The State Pattern ApplicabilitySolution
- An objects behavior depends on its state and it
must change its run-time behavior depending on
that state - Operations have large, multipart conditional
statement that depend on the objects state - Several operations contain the same conditional
structures based on one of more enumerated
constants representing the state the object is in - The state pattern puts each branch of the
conditional in a separate class so that an
objects state can be treated as an object in its
own right that can vary independently from other
objects
139(No Transcript)
140The State Pattern Participants
- Context
- Defines the interface of interest to the clients
- Maintains an instance of some ConcreteState that
defines the current state - State
- Defines an interface for encapsulating the
behavior associated with a particular state of
Context - ConcreteState subclasses
- Each subclass implements a behavior associated
with a state of the Context
141The State Pattern Collaborations
- Context delegates state-specific request to the
current ConcreteState object - A context may pass itself as an argument to the
State object handling the request allowing the
State object to access the Context if necessary - Context is the primary interface for clients.
Clients can configure a context with State
objects. Once the context configured, the clients
dont have to deal with the State objects
directly - Either Context or ConcreteState subclasses can
decide which state succeeds another
142The State Pattern Consequences
- Localises state-specific behavior and
partitions behavior for different states so that
new states and transitions can be added easily by
just adding new ConcreteState subclasses - /- Long procedures containing large conditional
statements are avoided but the number of classes
increases and the whole is less compact that a
single class - Makes state transitions explicit and protects
the context from inconsistent internal states
because the state update is atomic - When State object dont need instance variables
they can be shared they are then essentially
flyweights with no intrinsic state but only
behavior
143The State Pattern Implementation (1)
- Who defines the state transitions?
- If the criteria for state transition are fixed
they can be implemented entirely in the context - It is more flexible to let the State subclasses
specify their successor but (1) each State
subclass will al least know one other State
subclass introducing some implementation
dependencies between subclasses (2) the Context
must provide a interface to update the current
state - Creating and Destroying State object
- Create the State objects only when they are
needed ltgt Create the State objects ahead of time
and never destroy them - Depend on (1) whether all possible states are
known beforehand (2) the amount of information
that has to be stored in the State objects (3)
the frequency with which the state of a Context
changes
144The State Pattern Implementation (2)
- A table based alternative
- Use a table, mapping for each state, each
possible input, to the succeeding state - This approach converts conditional code into a
table-lookup and changing the transition criteria
is done by changing data (the table) instead of
changing code - Disadvantages are that (1) table lookup is often
less efficient that (virtual) function call and
(2) the table captures the state and the
transitions but needs to be augmented to perform
an arbitrary computation on each transition - Using dynamic inheritance
- Languages that allow to change an objects class
at run t