Design-Patterns Cheat Sheet
Design-Patterns Cheat Sheet
Class A
+ operationA()
+ operationX(parameter)
Class B
+ operationB()
+ operationY(parameter)
Class C
+ operationC()
1: contains objects from
subsystem
Link: Faade
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #11
FACTORY, ABSTRACT
A: are
implemented in
Concrete Factory B
+ produceProductA()
+ produceProductB()
Abstract Factory Definition
3: uses
Concrete Product A.b
Concrete Factory A
concrete factories
D: produces / return
Concrete Product A.a
Concrete Product B.b
Concrete Product B.a C: are extended /
implemented by
concrete products
abstract definitions
Base Product A
Base Product B
base product definitions
B: will produce
products of type
Client A
1: can use any factory based on
2: uses any of
Visual summary of the Abstract Factory Pattern
INTENT
Provide an interface for creating families of related
or dependent objects without specifying their
concrete classes.
DEPENDENCIES
Client A:
1: Can use any factory of abstract definitions
2: Uses any of Concrete Factory A, B ..
Abstract definitions:
A: Are implemented in Concrete Factory A, B
B: Will produce prodcuts of type Base Product A, B
Base Product A, B
C: Are extended / implemented by Concrete
Products
Concrete Factories A, B
D: Produces / return Concrete Products A.a, A.b,
B.a, B.b
RESULT
Blueprints for interchangeable factories with very
specific production lines producing specific
products
BASICS
WHEN/WHAT?
When you need to create a line of different factories
The Abstract Factory is a Pattern that describes how you can define the interfaces
for a set of factories you can interchange for any of the other, to produce very
specific products.
Blueprint for Concrete Factories
The Abstract Factory is basically a Blueprint for Concrete Factories. The Abstract
Factory Pattern uses this principle to create multiple Concrete Factories based on
the Abstract Factory and to allow you to choose any of them.
OTHER INFO
Different implementations of a Factory per context
The Abstract Factory Pattern becomes useful when your
code works within one or more specific Contexts, use the
same basic Products to perform its actions, but needs a
different Implementation for each specific Context.
Simple Factory is more to the point
If you do not need to create many different factories based
on the same template, use the Simple Factory instead.
CLASS DIAGRAM
interface / base class
Abstract Product A
+ someMethod()
+ anotherMethod()
Concrete Factory A.b
+ produceProductA()
+ produceProductB()
base class
Abstract Factory A
2.b: extends
3: uses
Override:
+ produceProductA()
+ produceProductB()
Concrete Factory A.a
Override:
+ produceProductA()
+ produceProductB()
return new Concrete
Product
2.a: produces
3: extends / implements
2.a: produces
interface / base class
Abstract Product B
+ someMethod()
+ anotherMethod()
Concrete Product B.b
4: extends /
implements
+ someMethod()
+ anotherMethod()
Client A 2.b: requests products of type
1.a: uses a factory of type
Concrete Product A.a
+ someMethod()
+ anotherMethod()
Concrete Product A.b
+ someMethod()
+ anotherMethod()
Link: Factory, Abstract
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #12
FACTORY METHOD
1: are
implemented in
Concrete Creator B
+ produceProductA()
+ produceProductB()
Factory Method Definitions
3: uses
Concrete Product A.b
Concrete Creator A
your classes
4: produces / return
Concrete Product A.a
Concrete Product B.b
Concrete Product B.a 3: are extended /
implemented by
concrete products
abstract definitions
Base Product A
Base Product B
base product definitions
2: will produce
products of type
Visual summary of the Factory Method Pattern
INTENT
Define an interface for creating an object, but
let subclasses decide which class to instantiate.
Factory Method lets a class defer instantiation
to subclasses.
DEPENDENCIES
Factory Method Definitions:
1: Are implemented in your classes
Factory Method Definitions:
2: Will produce products of type Base Product
A, B ..
Base Product A, B
3: Are extended / implemented by Concrete
Products
Concrete Creators A, B
4: Produces / return Concrete Products A.a,
A.b, B.a, B.b
RESULT
Re-usable definitions for factory methods to
produce concrete products in several classes
BASICS
WHEN/WHAT?
When you need to define a blueprint for Factory Methods
The Factory Method is mostly a way to define the blueprint with which you will create
Factory Methods within your own Classes.
Starting point for Abstract Factory
As you will find when you study the Abstract Factory Pattern, the Factory Method
Pattern is almost completely implemented there as well. The main difference is that the
Factory Method assumes you will implement the Factory Methods in your own
Concrete Classes, while the Abstract Factory assumes you will extract and abstract
these Factory Methods into separate Concrete Factories.
OTHER INFO
Simple Factory is more to the point
If you do not need to create blueprints for your Factory
Methods, but simply want to implement them, use the
Simple Factory instead.
CLASS DIAGRAM
interface / base class
Product A
+ someMethod()
+ anotherMethod()
Concrete Creator B
+ produceProductA()
+ produceProductB()
base class / interface
Creator
2.b: extends / implements
Concrete Product A.a
3: uses
+ someMethod()
+ anotherMethod()
+ doSomethingElse()
Override:
+ produceProductA()
+ produceProductB()
Concrete Product A.b
+ someMethod()
+ anotherMethod()
Concrete Creator A
+ doSomething()
Override:
+ produceProductA()
+ produceProductB()
return new Concrete
Product
2.a: produces
1.b: implements
2.a: produces
Link: Factory Method
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #13
FACTORY OBJECT MAP
3: maps / maps
constructors
for / constructs
FactoryObjectMap
+ static getObject( key, classRef )
+ static removeObject( key, classRef )
+ static addObject( key, classRef )
4: returns
instance of
object to
- static _objectMap
- static _objectConstructorMap
1: calls, using a key and class reference to
identify the specific object
Client
2: uses
Class A
Class B
Class C
objects of type
Visual summary of the Factory Object Map Pattern
RESULT
Creation and mapping of one instance of a specific
object of any type to be retrieved and used anywhere
INTENT
Ensures that each entity is represented only
once in your application by mapping them
against their identity and class reference.
Centralized lookup and creation of objects in and
from that map.
DEPENDENCIES
Client:
1: Calls Factory Object Map, using a key and
class reference to identify the specific object
getObject in Factory Object Map:
2: Uses Object Map to try and retrieve the
requested object, creates and maps new object
when Object Map does not contain object yet.
Object Map and Constructor Map:
3: Maps objects and constructors
getObject
4: Return instance of object to Client
BASICS
WHEN/WHAT?
When you want to encapsulate & control object mapping/object creation
The Factory Object Map encapsulates the object creation process. As it maps all
objects created before, it takes full control over that object creation. Due to the
encapsulation of the creation-process, the Factory Object Map automatically takes
care of mapping of newly create objects as well.
When you want only one instance of a specific entity
The Object Map holds all objects created during runtime. If and when you request
an object with a specific ID, it will attempt to resolve it from the map first. Only
when the object with that ID is not in the map, the Factory Object Map will
produce a new one.
Inversion of control and dependency injection
The Factory Object Map allows for implementations in which the concrete object
constructors are defined separately from the implementation of the Factory Object
Map, making is possible to change the concrete classes used for instantiation of
objects without impact on the implementation of the Factory Object Map or the
code using the Factory Object Map.
OTHER INFO
Extended Identity Map
The Extended Identity Map might as well have been called
Factory Identity Map when I wrote that variation down. It
does the same as the Factory Object Map, but in a more
simple structure.
One Factory Object Map to do it all
Like the Object Map, the Factory Object Map can be used to
store any and all maps you need in your application, limiting
the amount of Factory Objects Maps in your project to one.
Using Constants to identify the classes / base interfaces
Instead you could and probably should create and use
constants to identify and map the classes you use to create
and retrieve the objects.
CLASS DIAGRAM
Class A
Class B
Class C
objects of type
FactoryObjectMap
- static objectMap
- static objectConstructorMap
1: contains
+ static getObject( key, classRef )
+ static removeObject( key, classRef )
+ static addConstructor( constructor,
classRef )
+ static addObject( key, classRef )
static getObject( key:String , classReference ):
Get object of type and key from map
When not there yet: create and store object
return object;
Link: Factory Object Map
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #14
FACTORY, SIMPLE
+ produceProductA( subType )
+ produceProductB( subType )
Simple Factory
Concrete Product A.b
1: will produce
producs of type
Concrete Product A.a
Concrete Product B.b
Concrete Product B.a
2: are implemented as
concrete products
3: produces / return
Base Product B
Base Product A
base product definition
Visual summary of the Simple Factory Pattern
INTENT
Implement a method or class to create objects
based on specific parameters (the Context or
product type). The Simple Factory chooses and
instantiates the required class and returns the
result to the caller.
DEPENDENCIES
Simple Factory:
1: Will produce prod. of type Base Product A, B
Base Product A, B:
2: Are implemented on Concrete Products
Simple Factory Methods:
3: Produce / returns Concrete Products A.a, A.b,
B.a or B.b
RESULT
A very simple way to produce concrete products
based on specific parameters
BASICS
WHEN/WHAT?
To create a simple factory without the boilerplate code
You use the Simple Factory to create a factory without the
boilerplate-code of the Abstract Factory and Factory Method.
Instantiates objects based on a context
The Factory intantiates (produces) objects based on a specific
context or type. For instance, cars of type A, B and C which all
share the same interface, but each have a different implementation.
OTHER INFO
Can be implemented in separate Class or in your code
The Simple Factory can be implemented in your code or in a
separate Factory Class.
Returns products
Like its bigger brothers the Simple Factory produces and returns products.
Can have multiple factory methods
The Simple Factory allows you to inplement multiple factory methods.
Each factory method has an object subtype
Each method in the Simple Facotry produces one or more products of a
specific subtype. Each of these products share the same Interface but comes
from a differen Class and has a different implementation.
Useful for Builder, Parser and Interpreter
The Simple Factory is a very useful Pattern for the Builder, Parser and
Interpreter as it can produce the objects these Patterns need to build a
Composite structure.
CLASS DIAGRAM
3: uses
Simple Factory A
+ produceProductA( productType )
+ produceProductB( productType )
2.a: produces
case productTypeA:
return new
Concrete Product A
1.b: implements
Concrete Product A.a
+ someMethod()
+ anotherMethod()
Concrete Product A.b
+ someMethod()
+ anotherMethod()
interface / base class
Product A
+ someMethod()
+ anotherMethod()
Link: Factory, Simple
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #15
FLYWEIGHT *
Link: Flyweight
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #16
IDENTITY MAP
3: contains
Identity Map A
+ static getObject( objectID )
+ static addObject( objectID, object )
4: returns
instance of
object/null
value to
- static _objectIdentityMap
1.a: will try to get object from /
will insert new object into
2: uses
Class A
objects of type
1.c: will create
object from if no
object in map
data source
/ data objects
Type A
1.b: will request if
object not in map
Client
Visual summary of the Identity Map Pattern
INTENT
Ensures that each object gets loaded only once by
keeping every loaded object in a map. Looks up objects
using the map when referring to them.
DEPENDENCIES
Client:
1.a: Will try and get object form Identity Map A / will
insert ne object into Identity Map A
1.b: Will request object from data source / data objects
when not in map
1.c: Will create object from Class A if object not in map
getObject in Identity Map A:
2: Uses objectIdentityMap to retrieve object
Object Identity Map:
3: Contains objects of type Class A
Identity Map A:
4: Returns instance of object or null value to client
RESULT
A container for (data) objects which can be retrieved
once created,
so that each (data)item has one single object to contain
and represent it
BASICS
WHEN/WHAT?
Storing objects into a map
The Identity Map Pattern stores objects into a map, using an
identity to retrieve them again
Loading objects only once
The idea of the Identity map is to load objects only once. In the case
of a database, instead of requesting the same data-objects over and
over again from the external source, you only request the data
objects you do not have yet. This reduces the load on your backend-
system.
Centralizing data management
The Identity Map centralizes data management within your project. There
is only one class (per type of object) to address for the objects (of that type)
that you might want to use in your project. When using the Identity Map,
you are sure that the object you request is the only one representing that
specific entity with that specific ID.
OTHER INFO
Database only?
While the Identity Map is associated to be used in conjunction with a
database (or external data source), it is not the only use-case where you
might like and want to store objects under specific identities.
CLASS DIAGRAM
Identity Map A
- static objectIdentityMap
1: contains
objects of type
+ static getObject( objectID )
+ static removeObject( objectID )
+ static addObject( objectID , object )
static getObject( key:String , classReference ):
Get object of type and key from map
When not there yet: return null;
Class A
Link: Identity Map
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #17
INJECTOR *
Link: Injector
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #18
INTERPRETER
6: interpret
Non-terminal Expression A
Non-terminal Expression B
Object Structure A Client A
2: passes
context into
non-terminal expressions
5: can be child of
Terminal Expression A
Terminal Expression B
terminal expressions
4: can be child of
3: can contain
Semantic Context
1: has or receives a
Visual summary of the Interpreter Pattern
INTENT
Given a language, define a represention for its grammar along
with an interpreter that uses the representation to interpret
sentences in the language.
DEPENDENCIES
Client A:
1: Has or receives a Semantic context
2: Passes context into Object Structure A
Object Structure A:
3: Can contain non-terminal experssions and terminal
expressions.
Terminal expressions:
4: Can be child of non-terminal experessions
Non-terminal expressions:
5: Can be child of other non-terminal expressions
6: Can interpret (like the terminal ones) the Semantic Context
RESULT
An object structure interpreting and representing the
semantic relationships as present within the Semantic Context
Object
BASICS
WHEN/WHAT?
To interpret a semantic structure
The Interpreter takes a semantic structure and translates it into an
object model, representing that structure. The semantic structure
can be natural language, but also program-code and instructions
you can give to machines.
Deconstructing and interpreting semantic structure
Semantic structures are comprised of words or items of meaning
placed within a specific context and order. The context, order and
meaning of each individual item in the total structure combined
defines the meaning and intend of a sentence, line, paragraph,
method and set of instructions.
OTHER INFO
Composite pattern
The Interpreter creates a structure using objects with a very similar setup
as the Composite pattern.
Visitor
The Visitor pattern can be used to run through the composite object that is
the result of the interpretation, to read the structure and distill meaning
from it.
Compilers, bots, search engines and word processors
The Interpreter pattern can be used to create compilers; to create bots that
reply to queries from people; in search engines to break down your search
request and interpret the content from the pages the search bots spider; in
word processors to check if your sentences are setup properly.
CLASS DIAGRAM
base / abstract class
Abstract Expression A
+ interpret( context )
Terminal Expression A Nonterminal Expression A
2: extends
Client
Context
Override:
+ interpret( context )
Override:
+ interpret( context )
- parentExpression
1.a: uses /
injects Context
into object of
type
can create child elements
based on Context
is the terminal node on a
branch in the interpreted
Context
- childExpressions
3: are of type
1.a: has a
Link: Interpreter
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #19
MANAGER
3: has references to
Manager A
+ methodA():
do something
+ static methodB()
do something else
handlers
in subsystem
Concrete Handler A
Concrete Handler B
2: have references to
4: communicate to
5: delegates actions to specific
Client A, B, C
1: uses
Visual summary of the Manager Pattern
INTENT
Define an object that encapsulates and centralizes
Business Logic for a specific set of actions and acts as a
manager for the processes that happen in the subsystem.
Make these actions easily available to any object or Class
that needs it.
DEPENDENCIES
Client:
1: Uses Manager A
Manager A:
3: Has references to handlers in subsystem
5: Delegates specific actions to Concrete Handler A, B
Handlers in subsystem
2: Have references to Manager A
4: Communicate to Manager A
RESULT
Centralization of communication between objects and
centralized management of processes in your subsystem
BASICS
WHEN/WHAT?
Centralizing actions and Business Logic
The Manager Pattern centralizes actions on your system and the
business logic that otherwise would be scattered over your
sybsystem. It uses and addresses the subsystem in a similar way as
the Faade. It can be accessed directly and mediate further actions
like the Mediator.
Solve issues with Observer Pattern
Sometimes the use of the Observer Pattern can lead to a loss of
control: who dispatched what and why? Managers help centralize
the communication from different systems and create several hubs
with specific scopes of events and dispatches.
OTHER INFO
Faade and Mediator patterns combined
The manager can be seen as a merge of the Mediator and Faade pattern,
combining the aspects of both Patterns to create an object that allows you
for more control over your application.
The Business Logic: in the Manager or in separate classes?
The Business Logic can be put into separate classes as well within the
Manager itself.
Singleton or Multiton and keys
The Manager can implement either the Singleton or Multiton pattern to
offer a specific instance of the Manager. You address a specific instance
using the static methods and keys that identify the specific manager.
CLASS DIAGRAM
Handler A
Handler B
Manager A
+ someOperationD()
+ operationE(parameter)
+ operationF()
+ operationG(parameter)
+ requestA()
+ static requestB( reference )
+ static requestC( reference )
get concrete
manager by reference
handlerA
.someOperationD()
handlerB
.operationF()
- handlerA
- handlerB
4: contains a reference to / uses
5: contains a reference to /
uses
Contains business logic, or uses
external objects to handle
business logic
Client A
+ someOperationD()
1: calls / uses
Client B
+ someOperationE()
1: calls / uses
Client ..
+ someOperationF()
1: calls / uses
Link: Manager
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #20
MEDIATOR
3: has references to
Concrete Mediator
+ yourMethodA():
do something
+ yourMethodB()
do something else
colleagues
in subsystem
Concrete Collegue A
Concrete Collegue B
2: have references to
4: communicate to
5: delegates actions to specific
Client
1: uses
Visual summary of the Mediator Pattern
INTENT
Define an object that encapsulates how a set of objects
interact. Mediator promotes loose coupling by keeping
objects from referring to each other explicitly, and it lets
you vary their interaction independently.
DEPENDENCIES
Client:
1: Concrete Mediator
Concrete Mediator:
3: Has references to Concrete Colleagues in subsystem
5: Delegates specific actions to Concrete Collegues A, B
Concrete Collegues in subsystem
2: Have references to the Concrete Mediator
4: Communicate to the Concrete Mediator
RESULT
Centralization of communication between objects in your
subsystem
BASICS
WHEN/WHAT?
Centralization of communication between objects
More than wrapping the Classes and objects it wraps the
communication that takes place between them, by centralizing and
managing the communication that is needed for these Processes
within the Mediator
Hub or man in the middle
The Mediator acts as a hub or Man in the Middle for the
Communication between separate objects and Subsystems
Abstracts and decouples the dependencies between objects in
the subsystem. The Mediator allows objects in a Subsystem to
communicate between each other, without the need for these objects
to have knowledge of the other objects in the Subsystem.
OTHER INFO
Using Inversion of Control and Dependency Injection
The Mediator is another Pattern that applies the principles of Inversion of
Control. Instead of objects deciding who should be created and who will be
communicated to (the wiring), the Mediator takes over creation and the
wiring and successively Injects itself into each player.
Can Inject itself into the subsystem
In one of the possible implementations of the Mediator, the Mediator can
inject itself into the subsystem to be addressed directly by that Subsystem.
The benefits of this injection is simplification of the code and your
processes. De disadvantage is a tight coupling between the subsystem and
the (Interface of) the Mediator that is Injected.
CLASS DIAGRAM
Base Mediator A
Concrete Collegue A
+ operationA()
+ operationB(parameter)
base class
Base Collegue
1: contains a
reference to
- mediator
Concrete Collegue B
3: extends
Concrete Mediator A
+ someOperationD()
+ operationE(parameter)
+ operationF()
+ operationG(parameter)
+ requestA()
+ requestB()
+ requestC()
collegueA
.someOperationD()
collegueB
.operationF()
Concrete Mediator B
+ operationD()
- collegueA
- collegueB
2: extends
4: contains a
reference to
5: contains a
reference to
- collegueC
- collegueD
Link: Mediator
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #21
MULTITON *
Link: Multiton
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #22
OBJECT MAP
3: maps
ObjectMap
+ static getObject( key, classRef )
+ static removeObject( key, classRef )
+ static addConstructor( constructor,
classRef )
+ static addObject( key, classRef )
4: returns
instance of
object to
- static _objectMap
1: calls, using a key and class reference to
identify the specific object
Client
2: uses
Class A
Class B
Class C
objects of type
Visual summary of the Object Map Pattern
INTENT
Use one single point of entry to store objects of any
type in memory and retrieve them using a unique
identifier. Assure that only one instance of an object
exists for each specific data-item.
DEPENDENCIES
Client:
1: Calls ObjectMap using a key and class reference to
identify the specific object
Methods in Object Map:
2: Uses objectMap to perform their actions
Object Map:
3: Maps objects of type Class A, B, C under class
reference and identity key
getObject in Object Map
4: Returns an instance the object to the Client
RESULT
Mapping of one instance of a specific object of any type
to be retrieved and used anywhere
BASICS
WHEN/WHAT?
Centralizing data management
The Object Map centralizes data management within your project.
There is only one object and one class to address for all objects you
might use in your project. When using the Object Map, you are
sure that the object you request is the only one representing that
specific entity with that specific ID.
Storing objects in memory using two keys
The Object Map store objects in memory using two keys: the
Object Key (or ID) and a reference to the Class the object is derived
from.
Retrieving, re-using objects and allowing for data-persistence
The main goal of the Object Map is to make it easier to store
objects in such a way that you can retrieve them easily from
anywhere. This promotes re-use of objects and makes it easier to
create persistent objects with only one instance for data that comes
from the outside.
OTHER INFO
A pattern to de-couple dependencies
The Object Map has a second use, which is the de-coupling of dependencies
from objects and within your structure. Instead of sending specific objects
down a chain of objects, you can use abstract keys or identifiers(for instance
based on Constants or identifiers in XML or JSON data) that refer to the
specific objects you want and need.
Storing lists instead of objects
In some cases, instead of storing objects you might want to store lists of
objects, which you can access and modify anywhere in your application.
Factory Object Map
The Factory Object Mpa is a specific version of the Object Map, taking care
of obejct creation and mapping, instead of leaving this procures up to the
Client, increasing the level of control on the process.
CLASS DIAGRAM
Class A
Class B
Class C
objects of type
ObjectMap
- static objectMap
1: contains
+ static getObject( key, classRef )
+ static removeObject( key, classRef )
+ static addObject( key, classRef )
static getObject( key:String , classReference ):
Get object of type and key from map
When not there yet: return null
Link: Object Map
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #23
OBJECT POOL
3: contains
ObjectPool
+ static getObject( )
+ static addObject( recyclableObject )
4: returns
instance of
object or
null value
to
- static _objectPool
1.a: tries to get object first from / will
return object to
Client
2: uses
Class A
objects of type
1.b: will create
object from if no
object in pool
Visual summary of the Object Pool Pattern
RESULT
A container for objects which can be re-used
after they have been discarded, leading to a
reduction of new objects being created
INTENT
Manage the reuse of objects when a type of object is expensive
to create or only a limited number of a kind of object can be
created.
DEPENDENCIES
Client:
1.a: Will try to get object from the Object Pool / will return
object to object Pool when no longer needed
1.b: Will create object from Class A is nothing is in Object
Pool
getObject in Object Pool:
2: Uses object pool in static variable
4: Returns instance of object or null value to Client
Object Pool:
3: Contains objects of type Class A
BASICS
WHEN/WHAT?
When you want to reduce the amount
of new objects created to a minimum
The Object Pool allows you to recycle and re-use objects which
have already been created. This is possible by returning objects no
longer in use into the Object Pool.
Releasing the garbage collector
The Object Pool can be seen as a solution to bypass the garbage
collector. Instead of creating a lot of waste (your discarded objects)
you simply recycle what you already have and only create new
objects when your recycle-bin is empty.
Factory Object Pool: To centralize and manage Object
Creation
Instead of leaving it up to your code, the Factory Object Pool takes
complete care of the provision and management of object creation
OTHER INFO
Implementing recycle interface
Like with the Object Pool it is recommendable for your objects to
implement a recycle-interface and the code to reset the object and drop it
into the Object Pool. This way, when you kill the object, it will put itself
into the Object Pool. When and where you reset the object, so that it
returns to a clean state without any values from previous sessions.
Different ways to handle empty pools
There are three different ways to deal with an empty Pool: return a null
value (the Simple Object Pool), create and return a new object (I will refer
to this as the Factory Object Pool) and blocking the client until an object
becomes available from a different source (the Halting State Object Pool).
The gnarly issue of previous use
When an object is returned to the Object Pool, it has been used by other
objects and possibly event listeners are registered to the object and by the
object. References like this need to be broken to prevent unwanted behavior
to happen. One way to ease this up is by using the Smart Reference Proxy.
CLASS DIAGRAM
ObjectPool A
+ static getObject( )
+ static addObject( recyclableObject )
- static _objectPool < Class A >
1.a: get object from / will return
object to
Client
Interface: RecyclableObject
+ remove( )
+ reset( )
Class A
Implements:
+ pubic remove( )
+ public reset( )
+ someMethodA ( )
+ someMethodB ( )
1: contains
objects of type
2.b: can use static method to add
itself when rmeoved
2.a: implements
Link: Object Pool
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #24
OBSERVER
Observer A
Subject A 1: register
themselves to
2: will notify
registered
observers
Observer B
Observer C
subjects
Subject B
Subject C
Visual summary of the Observer Pattern
INTENT
Define a one-to-many dependency between objects so that
when one object changes state, all its dependents are notified
and updated automatically.
DEPENDENCIES
Observers:
1: Register themselves to one or more Subjects
Subjects:
2: Will notify registered Observers
RESULT
A more flexible way for objects to communicate with each
other
BASICS
WHEN/WHAT?
One object, Multiple Observers
One object can be Observed by many Observers.
Decoupling of Dependencies
The Observer object (or Subject) does not have to have any
relationship with the Observer, or has to know of the existence of
an of the (possible) Observers that will Observe the changes or
Events from the Subject
Events and Messages
The Observer Pattern can be used for two main types of
notification: Events and Messages.
OTHER INFO
Messages?
As discussed in the book, Messages can represent anything, including
Events, Requests, Updates and Instructions. Events are only dispatched
when something happened. Events can not be used to send requests or
instructions.
Event and Message Bus:
routing the Events and Messages through a specific bus
Instead of implementing the Obseerver Pattern directly on the object that is
to be observed, an alternative approach can be to use and refer to an Event
Bus. This Bus is an object to which Observers are bound and Events are
dispatched.
CLASS DIAGRAM
base class
Subject
+ attach( observer )
+ detach( observer )
+ notify()
Concrete Subject Concrete Observer
+ update()
- observerState
- subject
3.a: observes
+ update()
interface
Observer
2: extends
+ setState()
+ getState()
- subjectState
1: notifies object
based on
3.b: implements
for all observers in
list notify
- observerList
Link: Observer
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #25
PARSER
Abstract
Definition /
Object Tree
Object Tree /
Composite Object
Abstract Definition
1: parsed to
2: can be parsed to 3: can be parsed to
Visual summary of the Parser Pattern concept
INTENT
To convert or parse one structure into another structure:
containing similar, or the same, data.
DEPENDENCIES
Abstract Definition / Object Tree:
1: Can be parsed to Abstract Definition / Object Tree
Abstract definition:
2: Can be parsed to Abstract definition / Object Tree
Object Tree / Composite object:
3: Can be parsed to Abstract definition / Object Tree
RESULT
Any structure can be transformed into any other structure
BASICS
WHEN/WHAT?
To parse/convert one structure into another
The Parser can be used to parse or convert one structure into
another. This can be XML to objects or objects to XML or from one
abstract definition into another; for instance: XML to JSON and the
other way around. This can also mean one object structure into
another object structure, representing the same thing in a different
way. Think for instance of datagrams being parsed to visual elements
on screen.
To read and use the contents of a structure
Any structure contains data, and sometimes you need specific
elements from that data to be used or presented somewhere else. The
Parser can traverse the structure and distill those elements and pieces
of information you need.
OTHER INFO
Any direction
The Parser is by default a Pattern that can Parse anything to anything as
long as it is available and possible. So you can Parse one Abstract
Definition to another (XML to JSON, XML to a Custom Structure, XML
to a Custom Structure to an Object Tree, XML to an Object Tree, back to
XML).
Results can be fed back to a Parser
In principle, a Parser result can be Parsed into yet another structure. An
object structure can be parsed into an Abstract Definition and then into
another Abstract Definition and then into an object Tree.
Lossful and lossless parsing
Depending on your need and use, the parsing process can be either lossful
and lossless. Lossful means that from everything in A, only a part will
arrive in B. When you take B, structure A can never be recovered entirely.
Lossless means that there is no loss of information between A and B. A
can be converted to B and B back to A.
CLASS DIAGRAM
Parser A Simple Factory B Client
+ getObject( objectType ) + parse( structure )
2: uses / get
objects from
Base Composite Object
- children
+ addChild( )
Node Type A
Node Type B
2: extend
2.a: returns objects of type
2: uses
Link: Parser
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #26
PROTOTYPE *
Link: Prototype
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #27
PROXY
Real Subject A
Proxy
- realSubject
+ variableA
+ variableB
Client
- proxy
+ doSomething()
+ doSomethingElse()
1: contains
+ methodA( )
+ methodB( )
+ methodA( )
+ methodB( )
+ variableA
+ variableB
2: will contain
3: execute
5: will be
delegated to
4: can be passed to
Visual summary of the Proxy Pattern
INTENT
Provide a surrogate or placeholder for another object to
control access to it.
DEPENDENCIES
Client:
1: Contains Proxy
RealSubject in Client:
2: Will contain Real Subhect A
Methods in Client:
3: Execute methods on Proxy
Variables in Proxy:
4: Can be passed to variables in Real Subject A
Methods calls on Proxy:
5: Will be delegated to Real Subject A
RESULT
A separation between the user and the real object via a
man in the middle, allowing you to control access to it
BASICS
WHEN/WHAT?
Representing something that might not be there yet
The object we represent with the Proxy is usually not yet there when
we instantiate the Proxy.
Can be used immediately, even if the object is not there
With the Proxy you do not have to wait for the Actual object to
arrive. Whatever you want to do with the object can be done
immediately on the Proxy.
Different types
Remote Proxy: representing an object from somewhere else
Virtual Proxy: creating the object when needed
Protection Proxy: enveloping and protecting the original object
Smart Reference: man in the middle when accessing an object
OTHER INFO
Pretends to be, with additional features
Like the Adapter and the Bridge, the Proxy Pretends to be the object it
represents. But where Bridge and Adapter rely on the actual object to be
there, for the Proxy it does not matter if the object it represents arrives
later or not at all
Buffering the values and method calls
The Proxy in most cases will act as a buffer for all the method calls
and value settings on the actual object. While the actual object is not
there, the Proxy will store these settings and queue the calls internally.
Passes all your requests when the object is there
Once the object arrives, the Proxy passes all your requests and executes
your settings on the object (B)
CLASS DIAGRAM
Real Subject A
+ executeA( )
+ executeB( )
interface
Subject A
Proxy A
- realSubject
+ variableA
+ variableB
2.a: implements
Client
- proxy
+ doSomething()
+ doSomethingElse()
1: is of type
+ executeA( )
+ executeB( )
+ executeA( )
+ executeB( )
if realSubject != null:
realSubject.executeA()
3: instanitates /
passes values to /
delegates actions to
proxy.executeA()
proxy.executeB()
+ variableA
+ variableB
Link: Proxy
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #28
REFLECTION *
Link: Reflection
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #29
SINGLETON
Singleton
+ static instance()
+ someMethod()
+ anotherMethod()
4: returns
instance of
object to
- static _instance
3: contains
instance of
1: calls
Client
2: uses
Visual summary of the Singleton Pattern
INTENT
Provide a surrogate or placeholder for another
object to control access to it.
DEPENDENCIES
Client:
1: Calls static method instance()
Static Methods instance():
2: Uses the instance stored in the static variable
_instance or created new instance when not there.
Static method :
3: Execute methods on Proxy
Variables in Proxy:
4: Can be passed to variables in Real Subject A
Methods calls on Proxy:
5: Will be delegated to Real Subject A
RESULT
One single instance of an object that can be retrieved
and used anywhere
BASICS
WHEN/WHAT?
Provide one single instance of an object
The Singleton is used to provide one single instance of an object
throughout your project.
Replacement for global variables
One use for the Singleton is as a replacement for global variables. The
basic idea is that you want to have one single central place to store
specific values and references to other objects in such a way that you
can reach this from all over your application.
For parts of the system that require only one instance
Some parts of your system require one and only one instance of an
object as this instance should be the only one dealing with that
subject and information. In games this can be your game-score and
player health. In an OS this can be the file system or a printer spooler.
OTHER INFO
The Multiton, Identity Map and Object Map:
taking it one step further
The Multiton, Identity Map and Object Map do roughly the same as the
Singleton: providing only one instance, but then per entity. For instance:
in a multiplayer game, you have player 1 and player 2 and each need
their own object and representative.
Unit testing
The Singleton is kind of suspect in unit testing as you do not control
the instantiation. Nothing prevents you, however, from injecting a
controlled version of the singleton instance into the singleton class.
CLASS DIAGRAM
Singleton
+ static instance( )
+ someMethod()
- static _instance
1: contains
reference to
Link: Singleton
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #30
STATE
Context
+ request()
+ setState( stateOject )
Concrete State A
+ handleRequest()
- stateObject
Concrete State B
+ handleRequest()
state object
1: contains
2: is handled by current
5: sets next state object via
3: has reference to /
can inject another
state object into
4: has knowledge
of other
Concrete State C
+ handleRequest()
Visual summary of the State Pattern
INTENT
Allow an object to alter its behavior when its
internal state changes. The object will appear to
change its class.
DEPENDENCIES
State Object in Context:
1: Contains Sate Object
Request in Context:
2: Is handled by State Object
State Object :
3: Has reference to / can inject another object into
Context
4: Has knowledge of other State Objects
5: Sets next State Object via setState mehtod
RESULT
A self-organizing delegator that defines internally
which concrete implementation should handle the
next state of the process
BASICS
WHAT/WHEN?
When you need a self-organizing delegator to handle processes
Due to its setup, the State can be seen as a self-organizing Delegator.
The Context delegates actions to the State object. The State object
then defines which next State object will deal with the process state
that follows.
The State object changes the content of the State container
The State Pattern is a closed universe. Your code, using the State
Pattern, has no knowledge on what State should or could be next.
This is all dealt with by the State objects themselves.
OTHER INFO
Each state object knows what next state will follow
Each state object knows what next state will follow on a specific method
call.
Actions in the Context are delegated to the State object
Most if not all actions in the Context are delegated to the State object.
State objects have knowledge of other State objects
State objects have knowledge of other State objects and which State
object to choose when the State changes due to a method call.
CLASS DIAGRAM
Context
+ request()
+ setState( stateOject )
Concrete State A
+ handle()
- stateObjectB
+ setContext( context )
+ handle()
base class
State
1: contains
object of type
stateObject.handle()
- stateObject
Concrete State B
+ handle()
- stateObjectA
2.a: extends
- contextObject
contextObject.setState( stateObjectB )
2.b: has reference to /
sets next state object in
Link: State
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #31
STRATEGY
Your Class
+ yourMethodA():
if A:
do Approach A
if B:
do Approach B
+ yourMethodB()
variables
procedures
Concrete Strategy A.a
+ yourMethodA:
do Approach A
Concrete Strategy A.b
+ yourMethodA:
do Approach B
1: extract and
split conditional
code into separate
classes
2: injected into /
replacement for: code
inside yourMethodA
Visual summary of the Strategy Pattern
INTENT
Define a family of algorithms, encapsulate each one,
and make them interchangeable. Strategy lets the
algorithm vary independently from clients that use
it.
DEPENDENCIES
Actions in Your Class:
1: Extracted and split into separate classes
Strategies:
2: Injected into / replacement for code inside your
method
RESULT
Classes and Objects that can change part of their
behavior
BASICS
WHAT/WHEN?
When only a part of the process changes in a specific Context
The Strategy Pattern is used when only a part of the process in your
Class changes in a specific Context.
When you want to extract Context specific code into a separate
Class
To cater a more dynamic implementation of specific routines, only the
context-specific code is externalized (extracted) into a Strategy Class.
Depending on the Context of the situation, a different Strategy can be
injected into the Context object by your code, leading to a different
execution of specific actions.
A handy alternative for conditional execution in your code
Instead of cluttering your methods with conditions, you can simply
extract that conditional code into separate Classes, select the one you
need and delegate the concrete execution to it.
OTHER INFO
Delegating actions
Like the Bridge and the Delegate Pattern, the Strategy Pattern delegates
actions to another object. In the case of Strategy, this is the Strategy
Object or concrete implementation of the Strategy per Context.
CLASS DIAGRAM
Context
+/- executeA()
+ setStrategyA( strategy )
+ doSomethingElse()
Concrete Strategy A.a
+ executeA()
+ executeA( )
interface
Strategy A
2.a: contains
object of type
strategyA.executeA()
- strategyA
Concrete Strategy A.b
+ executeA()
2.a: implements
Client
- context
- setStrategy(
contextID)
1: uses / can set
strategy
2.b: uses
Link: Strategy
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #32
TEMPLATE METHOD *
Link: Template Method
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF
DESIGN PATTERNS #33
VISITOR
Concrete Element A
Concrete Element B
Concrete Visitor A
Object Structure A
Concrete Visitor B
Client A
visitors
1: selects a concrete visitor based on 2: has / sends selected visitor into
elements
3: consists of elements based on
4: visits / is sent through /
can perform operations on
5: can be child of
Visual summary of the Strategy Pattern
INTENT
Represent 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.
DEPENDENCIES
Client A:
1: Selects a concrete visitor A, B
2: Has / sends selected visitor into Object Structure A
Object Structure A:
3: Consists of (composite) elements bases on Concrete
Element A, B
Visitors:
4: Visits / is sent through / can perform operation on
elements in Object Structure A
Elements in Object Structure A:
5: Can be child of other elements
RESULT
A dynamic solution to run through- and perform actions on
an Object Structure from the inside using different type of
visitors
BASICS
WHAT/WHEN?
When you need to traverse through a composite object
The Visitor can be used to travers through a Composite object and
either do something with the object,s or simply read the contents.
As an alternative for the Parser
You could use the Visitor pattern as an alternative for the Parser as
both can accomplish the same results. The Visitor requires a bit more
within the objects you traverse.
Many different Visitors, one traversing process
The benefit of the Visitor is that you can use many different Visitors
in the same traversing process, each delivering a completely different
result in that process.
OTHER INFO
Can require specific setup of the objects in the tree
In the basic implementation of the Visitor Pattern, the objects pass the
Visitor. This includes an accept method on each object: accepting the
visitor.
Visitor can pass itself to the next object
There are workarounds possible in which the Visitor can pass itself to
each next object and deal with the content there. One workaround is to
use an Object Adapter for the objects which are not implementing the
Visitor Pattern.
Inverted approach related to the Parser
Like the Command and Observer patterns, the Visitor and Parser are two
different approaches to the same problem: how do I work with data and
objects in a structure? The Visitor inverts the process by traversing from
the inside
CLASS DIAGRAM
interface / base class
Base Visitor A
Concrete Element A
+ acceptVisitor( visitor )
+ acceptVisitor( visitor )
base class
Base Element A
Concrete Element B
3.a: extends
Concrete Visitor A
3: consists of elements based on
+ acceptVisitor( visitor )
Object Structure A
- childElementList
Overrides / Implements:
+ handleElementA( elementA )
+ handleElementB( elementB )
Concrete Visitor B
visitor.handleElementA(
this )
visitor.handleElementB(
this )
+ handleElementA( elementA )
+ handleElementB( elementB )
2: extends / implements
Client A
1.a: selects a concrete
visitor based on
1.a: sends selected
visitor into
Overrides / Implements:
+ handleElementA( elementA )
+ handleElementB( elementB )
3.b: contains
elements
based on
Link: Visitor
All text and images Peter Kaptein. Version: June 2012. No permission needed to copy, distribute, print and use this PDF