SlideShare a Scribd company logo
Design Patterns
illustrated
Herman Peeren, March 17, 2015
(Design Patterns illustrations: Nelleke Verhoeff, 2010)
in this presentation I also used some UML-diagrams
from these handy UML-reference cards:
http://www.mcdonaldland.info/2007/11/28/40/
Design Patterns
●● recipes against common (OO-) programming problems
●● code reuse: no need to reinvent the wheel
●● common language
●● GOF: 23 “classical” patterns
classic,
The Book
四人帮
The one constant in software development:
CHANGE!
The one constant in software development:
CHANGE!
The one constant in software development:
I knew it ...
Ideal: code as modular black boxes
Single responsibility principle
Open for extension, closed for modification
Liskov subsitution principle
Interface segregation
Dependency inversion
Avoid: tight coupling!
It might get you into trouble...
Code
smells!
Beware of:
some code smells:
►► duplicate code
►► long method
►► large class
►► combinatorial explosion
►► conditional complexity
►► switch statements
►► indecent exposure
Code often starts simple
But “grows”:
►► more methods in a class
►► longer methods
►► more if then but if then while x>0 or and etc.
►► more classes, that depends on other classes
and becomes more complex
Example: a shopping cart
►► implement putting products in the cart
►► start with some pay() method
►► if paypal then..., if iDEAL then...
►► let’s extract a payment interface
►► with several implementations (paypal, iDEAL, etc)
►► mutually exclusive choices
each choice is a “strategy” (hurray, our first pattern!)
Encapsulate what varies
Strategy pattern
For instance: different payment possibilities at checkout
Replace Conditional Logic with Strategy
if ($income <= 10000) {
return $income*0.365;
} else if ($income <= 30000) {
return ($income-10000)*0.2+35600;
} else //etc (...)
return ($income-60000)*0.02+105600;
} // note: mutual exclusive grouping
if ($income <= 100000) {
$strategy = new InsuranceStrategyLow($income);
} else if ($income <= 300000) {
$strategy = new InsuranceStrategyMedium($income);
} else //etc (...)
$strategy = new InsuranceStrategyVeryHigh($income);
}
return $strategy->calculateInsurance();
http://wiki.jetbrains.net/intellij/Replace_conditional_logic_with_strategy_pattern
Strategy
When something can be done in several ways, make those
ways interchangeable.
POSSI-
BILITIES
c©yepr
State example: states of a document
►► a draft doesn’t need a depublish() method
►► a published document doesn’t need a publish() method
or states of a shopping-cart
►► while shopping you don’t need a pay() method
►► but you need methods to put product in or out the cart
►► when paid you don’t need a pay() method
►► nor put_product_in_cart()
State
Let an object show other methods
after a change of internal state (as if it changes it’s class).
in a.....hick......different state,
....hick....I behave differently....hick.....
c© yepr
Bridge example: payment and payment providers
Bridge
Decouple an abstraction from its implementation.c
COLA
COLA
COLA
COLA
1 LITER
1 LITER
COLA
MILK
MILK
1 LITER
1 LITER
MILK
©yepr
Create those objects
Factory method example: different kinds of customers...
...with different kinds of invoices
Factory Method
Provide an interface for the creation of objects.
Allow subclasses to “decide” which class to instantiate.
c©yepr
Abstract factory example:
a Gold customer, cart, invoice, etc.
Abstract Factory
Povide an interface for creating families of related
or dependent objects. A factory for factories.
c©yepr
Building (complex) objects
Example: DI-container
Other example:
documentbuilder (for tree-like structures):
/$domtree = new DOMDocument(‘1.0’, ‘UTF-8’);
/* create the root element of the xml tree */
$xmlRoot = $domtree->createElement(“xml”);
/* append it to the document created */
$xmlRoot = $domtree->appendChild($xmlRoot);
$currentTrack = $domtree->createElement(“track”);
$currentTrack = $xmlRoot->appendChild($currentTrack);
// etc...
Builder
Seperate the construction process (how) of a complex object
from the concrete representations (what).
c©yepr
Encapsulate what doesn’t vary...
Template Method
The skeleton of an algorithm is fixed,
but parts can be filled in differently.
c©yepr
Add behaviour
►► but respect the Open-Closed principle
Decorator
In PHP you can use __call to copy parent methods:
public function __call($method, $args) {
return call_user_func_array(
array($this->decoratedInstance, $method),
$args
);
}
N.B.: Magic functions are magic...
but come at a cost!
Decorator
Add extra functionallity (at runtime),
while keeping the interface the same.
Matroushka’s...
c©yepr
Move Accumulation to Visitor
Visitor
Make a kind of plugin-possibility for methods:
in that way methods can be added in runtime.
printservice!
c©yepr
Composite
Create a tree structure for part-whole hierarchies.
A node is also a (part of a) tree. Recursive:
c©yepr
Interfacing
Unify interfaces with Adapter:
For instance: different payment gateways
(PayPal, iDEAL, Hipay, Moneybookers, etc.)
Instead of different interfaces
refactor to
one preferred interface
and write adapters for the others
Adapter (= Wrapper)
Adapt an interface to an expected interface.c©yepr
Proxy
Provide a surrogate or placeholder for another object
to control access to it.
c©yepr
Facade
Provide a general (simpler) interface for a set of interfaces.
looks
simple
c©yepr
Decoupling
Observer
Notify “subscribers” of changes.
WHO?
ME
ME
MENO
c©yepr
Mediator
Layer in between: communication via one object.c©yepr
Undo
Memento
Save and restore the internal state of an object.
ME
c©yepr
Sequence of actions
Chain of Responsibility
Define a method of passing a request among a chain of objects.c©yepr
A command is an object to execute 1 method
Decoupling (Symfony2) Forms from Entities:
http://verraes.net/2013/04/decoupling-symfony2-forms-from-entities/
Chain of Command: Chain of Responsability with Commands
Replace Conditional Dispatcher with Command
if ($actionName == NEW_WORKSHOP) {
//do a lot
} else if ($actionName == ALL_WORKSHOPS) {
// do a lot of other things
} // and many more elseif-statements
NewWorkshopHandler, AllWorkshopsHandler, etc.
Command
Encapsulate a command request in an object.c
YOU,DO YOUR
TASK!
LIGHT
OFF
LIGHT
ON
TASKTASK
©yepr
Leftovers
Flyweight
Use one instance of a class
to provide many “virtual” instances.
c©yepr
PHP: SPL iterators
►► http://www.php.net/manual/en/class.iterator.php
►► http://www.php.net/manual/en/spl.iterators.php
Stefan Froelich:
►► http://www.sitepoint.com/using-spl-iterators-1/
►► http://www.sitepoint.com/using-spl-iterators-2/
Anthony Ferrara video:
►► http://blog.ircmaxell.com/2013/01/todays-programming-with-anthony-vi-
deo.html
Iterator
Enable sequential access to collection elements, without showing
the underlying data-structures (array, list, records, etc)
nextnext
next
c©yepr
Replace implicit language with Interpreter:
search-methods including combinations:
►► belowPriceAvoidingAColor( )
►► byColorAndBelowPrice( )
►► byColorSizeAndBelowPrice( )
interpretable expression:
$productSpec =
new AndSpec(
new BelowPriceSpec(9.00),
new NotSpec(newColorSpec(WHITE))
);
“You don’t need an Interpreter for complex languages
or for really simple ones.” (Joshua Kerievsky)
Interpreter
Domain -> (little) language -> grammar -> objects (DSL)
he means:
do this, do that,
and after finishing it,
go there!
HÉ!HÉ!
c©yepr
Javascript:
var Person = function() { // bladibla };
var Customer = function(name) {
this.name = name;
};
Customer.prototype = new Person();
Prototype in PHP:
►► adding properties is easy
►► adding behaviour is less obvious, but...
►► CLOSURES can help here, with some (dirty) tricks
Prototype
Make variations on copies of a basic-object.
COPY-SERVICE
c©yepr
Singleton
Ensure a class only has one instance, and provide a global
point of access to it.
Oh, I’m so
loooooooonly
c©yepr
Singleton
Ensure a class only has one instance, and provide a global
point of access to it.
Did anybody say GLOBAL???
Oh, I’m so
loooooooonly
c
BANNED!
©yepr
“Every
advantage
has its
disadvantages”
(free to Johan Cruyff,
Dutch Football Pattern Designer
and Ajax-fan...)
Résumé
Classic pattern categories
creational, structural and behavioral patterns:
►► creational: object instantiation
►► structural: larger structures of classes or objects
►► behavioral: interaction and distribution of responsibility
Other categorisations
Loek Bergman (dev. from Rotterdam):
►► transformational
►► transportational
►► translational
Anthony Ferrara:
►► Shim : not necessary (for PHP)
►► decompositional: breaking objects apart
►► compositional: making things simpler by assembling
http://loekbergman.nl/InsideArchitecture
http://blog.ircmaxell.com/2013/09/beyond-design-patterns.html
Creational design patterns
►► Factory Method: Allow subclasses to “decide” which class
to instantiate.
►► Abstract Factory: Encapsulate a set of analo-
	 gous factories that produce families of objects.
►► Builder: Encapsulate the construction of com-
	 plex objects from their representation; so, the
	same building process can create various repre-
	 sentations by specifying only type and content.
►► Singleton:	 Ensure that only a single instance of
	a class exists and provide a single method for
	gaining access to it.
►► Prototype: Create an initialized instance for
	cloning or copying.
Factory Method
Provide an interface for the creation of objects.
Allow subclasses to “decide” which class to instantiate.
c©yepr
Abstract Factory
Povide an interface for creating families of related
or dependent objects. A factory for factories.
c©yepr
Builder
Seperate the construction process (how) of a complex object
from the concrete representations (what).
c©yepr
Singleton
Ensure a class only has one instance, and provide a global
point of access to it.
Oh, I’m so
loooooooonly
c©yepr
Singleton
Ensure a class only has one instance, and provide a global
point of access to it.
Did anybody say GLOBAL???
Oh, I’m so
loooooooonly
c
BANNED!
©yepr
Prototype
Make variations on copies of a basic-object.
COPY-SERVICE
c©yepr
Structural design patterns
●● Adapter: Adapt an interface to an expected interface.
●● Bridge: Decouple an interface from its implementation.
●● Composite: Create a tree structure for part-whole hierarchies.
●● Decorator: Extend functionality dynamically.
●● Facade: Simplify usage by defining a high-level interface.
●● Flyweight: Support fine-grained objects 	efficiently by sharing.
●● Proxy: Represent an object with another object for access control.
Adapter (= Wrapper)
Adapt an interface to an expected interface.c©yepr
Bridge
Decouple an abstraction from its implementation.c
COLA
COLA
COLA
COLA
1 LITER
1 LITER
COLA
MILK
MILK
1 LITER
1 LITER
MILK
©yepr
Composite
Create a tree structure for part-whole hierarchies.
A node is also a (part of a) tree. Recursive:
c©yepr
Decorator
Add extra functionallity (at runtime),
while keeping the interface the same.
Matroushka’s...
c©yepr
Facade
Provide a general (simpler) interface for a set of interfaces.
looks
simple
c©yepr
Flyweight
Use one instance of a class
to provide many “virtual” instances.
c©yepr
Proxy
Provide a surrogate or placeholder for another object
to control access to it.
c©yepr
Behavioral design patterns
●● Chain of Responsibility: Define a method of passing a
request among a chain of objects.
●● Command: Encapsulate a command request in an object.
●● Interpreter: Allow inclusion of language elements in an appli-
cation.
●● Iterator: Enable sequential access to collection elements.
●● Mediator: Define simplified communication between classes.
●● Memento: Save and restore the internal state of an object.
●● Observer: Define a scheme for notifying objects of changes to
another object.
●● State: Alter the behavior of an object when its state changes.
●● Strategy: Encapsulate an algorithm inside a class.
●● Template Method: Allow subclasses to redefine the steps of
an algorithm.
●● Visitor: Define a new operation on a class without changing it.
Command
Encapsulate a command request in an object.c
YOU,DO YOUR
TASK!
LIGHT
OFF
LIGHT
ON
TASKTASK
©yepr
Chain of Responsibility
Define a method of passing a request among a chain of objects.c©yepr
Interpreter
Domain -> (little) language -> grammar -> objects (DSL)
he means:
do this, do that,
and after finishing it,
go there!
HÉ!HÉ!
c©yepr
Iterator
Enable sequential access to collection elements, without showing
the underlying data-structures (array, list, records, etc)
nextnext
next
c©yepr
Mediator
Layer in between: communication via one object.c©yepr
Memento
Save and restore the internal state of an object.
ME
c©yepr
Observer
Notify “subscribers” of changes.
WHO?
ME
ME
MENO
c©yepr
State
Let an object show other methods
after a change of internal state (as if it changes it’s class).
in a.....hick......different state,
....hick....I behave differently....hick.....
c© yepr
Strategy
When something can be done in several ways, make those
ways interchangeable.
POSSI-
BILITIES
c©yepr
Template Method
The skeleton of an algorithm is fixed,
but parts can be filled in differently.
c©yepr
Visitor
Make a kind of plugin-possibility for methods:
in that way methods can be added in runtime.
printservice!
c©yepr
Some books
GOF: 23 “classical” patterns:
classic,
The Book
fun!
good start
Dec. 2013
Simple
Febr.
2013
Selection
PHP-
examples
PHP and Design Patterns
Fowler:
architectural patterns
for
enterprise applications
Fowler: also
known from
refactoring
Kerievsky:
refactoring
to patterns
PEAA & Refactoring
Resign Patterns:
Ailments of Unsuitable Project-Disoriented Software
Questions?
Contact info:
Herman Peeren
herman@yepr.nl
© Yepr
Design Pattern Illustrations: Nelleke Verhoeff, Red Cheeks Factory, 2010
Creative Commons Public License for noncommercial use
http://creativecommons.org/licenses/by-nc/3.0/legalcode

More Related Content

PDF
Design patterns illustrated 010PHP
PDF
Design Patterns Illustrated
PDF
The 23 gof design patterns in java ,the summary
PDF
Object-oriented Basics
PDF
Creational Design Patterns
PPT
JAVA design patterns and Basic OOp concepts
PPTX
OOP, API Design and MVP
PDF
Patterns for JVM languages - Geecon 2014
Design patterns illustrated 010PHP
Design Patterns Illustrated
The 23 gof design patterns in java ,the summary
Object-oriented Basics
Creational Design Patterns
JAVA design patterns and Basic OOp concepts
OOP, API Design and MVP
Patterns for JVM languages - Geecon 2014

What's hot (20)

PPTX
Javascript Design Patterns
PPTX
Object oriented javascript
PPT
P Training Presentation
PPTX
Introduction to Design Patterns in Javascript
PPTX
Js: master prototypes
PPTX
Javascript best practices
PPT
Design Patterns
PPTX
JavaScript OOPS Implimentation
PDF
JavaScript Programming
PPTX
OOPs in Java
PPT
Object Oriented Programming with Java
PPT
Java oops PPT
PDF
JAVA PROGRAMMING- Exception handling - Multithreading
PPT
PHP - Introduction to Object Oriented Programming with PHP
PPT
Java oops and fundamentals
PPT
Patterns In-Javascript
PPTX
Inheritance Mixins & Traits
PPTX
Class introduction in java
PDF
Model Manipulation Using Embedded DSLs in Scala
PPTX
OOPS in Java
Javascript Design Patterns
Object oriented javascript
P Training Presentation
Introduction to Design Patterns in Javascript
Js: master prototypes
Javascript best practices
Design Patterns
JavaScript OOPS Implimentation
JavaScript Programming
OOPs in Java
Object Oriented Programming with Java
Java oops PPT
JAVA PROGRAMMING- Exception handling - Multithreading
PHP - Introduction to Object Oriented Programming with PHP
Java oops and fundamentals
Patterns In-Javascript
Inheritance Mixins & Traits
Class introduction in java
Model Manipulation Using Embedded DSLs in Scala
OOPS in Java
Ad

Viewers also liked (9)

PDF
Palestra ASP.NET MVC
PPT
Design patterns - Strategy Pattern
PDF
Hello world e4 application part 5
PDF
Lesson 13 demonstrative pronouns
PDF
Mobile games
PDF
Padroes De Projeto
PDF
Exemplos de Design Patterns em Java
PPTX
Gof design patterns
PPS
Design Patterns For 70% Of Programmers In The World
Palestra ASP.NET MVC
Design patterns - Strategy Pattern
Hello world e4 application part 5
Lesson 13 demonstrative pronouns
Mobile games
Padroes De Projeto
Exemplos de Design Patterns em Java
Gof design patterns
Design Patterns For 70% Of Programmers In The World
Ad

Similar to Design patterns illustrated-2015-03 (20)

PPTX
Introduction to Design Patterns
PDF
Designpatterns illustrated
PDF
Reviewing OOP Design patterns
PPS
Jump start to OOP, OOAD, and Design Pattern
PPT
Jump Start To Ooad And Design Patterns
PDF
Java Programming
PDF
Design Patterns in Cocoa Touch
PDF
27418524 design-patterns-dot-net-with-examples
PPTX
Design Patterns
PDF
Dependency Inversion and Dependency Injection in PHP
PPTX
Software Architecture and Design Patterns Notes.pptx
PPT
Object Oriented Concepts and Principles
PPT
10-design-patterns1.ppt.software engineering
PPTX
Design patterns in brief
PPTX
Framework Design Guidelines For Brussels Users Group
PDF
Developing maintainable Cordova applications
PDF
Design patterns in javascript
PDF
.NET for hackers
DOCX
C# Unit 2 notes
Introduction to Design Patterns
Designpatterns illustrated
Reviewing OOP Design patterns
Jump start to OOP, OOAD, and Design Pattern
Jump Start To Ooad And Design Patterns
Java Programming
Design Patterns in Cocoa Touch
27418524 design-patterns-dot-net-with-examples
Design Patterns
Dependency Inversion and Dependency Injection in PHP
Software Architecture and Design Patterns Notes.pptx
Object Oriented Concepts and Principles
10-design-patterns1.ppt.software engineering
Design patterns in brief
Framework Design Guidelines For Brussels Users Group
Developing maintainable Cordova applications
Design patterns in javascript
.NET for hackers
C# Unit 2 notes

More from Herman Peeren (19)

PDF
ProjectionalForms-2023-11-14.pdf
PDF
ExtensionGenerator-JoomlaDagen2023-slides.pdf
PDF
Cut & Shave
PDF
Programmeren, talen en het begrijpen van de wereld
PDF
Dci in PHP
PDF
Improve our PHP code with ideas from Functional Programming
PDF
DCI DDD-BE April 2015
PDF
Event Sourcing
PDF
Next Generation Joomla!
PDF
Behat, Behavioral Driven Development (BDD) in PHP
PDF
Print, geen kunst aan
PDF
Jooctrine - Doctrine ORM in Joomla!
PDF
#jd12nl Joomla 2.5 extensies
PDF
#jd12nl Seblod 2
PDF
Jug010 120320-templates
PDF
Joomla2.0 architecture
PDF
Webservices: connecting Joomla! with other programs.
PDF
Commercial gpljoomla
PPS
Flash templates for Joomla!
ProjectionalForms-2023-11-14.pdf
ExtensionGenerator-JoomlaDagen2023-slides.pdf
Cut & Shave
Programmeren, talen en het begrijpen van de wereld
Dci in PHP
Improve our PHP code with ideas from Functional Programming
DCI DDD-BE April 2015
Event Sourcing
Next Generation Joomla!
Behat, Behavioral Driven Development (BDD) in PHP
Print, geen kunst aan
Jooctrine - Doctrine ORM in Joomla!
#jd12nl Joomla 2.5 extensies
#jd12nl Seblod 2
Jug010 120320-templates
Joomla2.0 architecture
Webservices: connecting Joomla! with other programs.
Commercial gpljoomla
Flash templates for Joomla!

Recently uploaded (20)

PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PPTX
history of c programming in notes for students .pptx
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
System and Network Administration Chapter 2
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
L1 - Introduction to python Backend.pptx
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Understanding Forklifts - TECH EHS Solution
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
history of c programming in notes for students .pptx
2025 Textile ERP Trends: SAP, Odoo & Oracle
System and Network Administration Chapter 2
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Upgrade and Innovation Strategies for SAP ERP Customers
L1 - Introduction to python Backend.pptx
CHAPTER 2 - PM Management and IT Context
Softaken Excel to vCard Converter Software.pdf
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Odoo Companies in India – Driving Business Transformation.pdf
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Reimagine Home Health with the Power of Agentic AI​
Wondershare Filmora 15 Crack With Activation Key [2025
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
How to Choose the Right IT Partner for Your Business in Malaysia
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Understanding Forklifts - TECH EHS Solution

Design patterns illustrated-2015-03

  • 1. Design Patterns illustrated Herman Peeren, March 17, 2015 (Design Patterns illustrations: Nelleke Verhoeff, 2010) in this presentation I also used some UML-diagrams from these handy UML-reference cards: http://www.mcdonaldland.info/2007/11/28/40/
  • 2. Design Patterns ●● recipes against common (OO-) programming problems ●● code reuse: no need to reinvent the wheel ●● common language ●● GOF: 23 “classical” patterns classic, The Book 四人帮
  • 3. The one constant in software development:
  • 4. CHANGE! The one constant in software development:
  • 5. CHANGE! The one constant in software development: I knew it ...
  • 6. Ideal: code as modular black boxes
  • 7. Single responsibility principle Open for extension, closed for modification Liskov subsitution principle Interface segregation Dependency inversion
  • 9. It might get you into trouble...
  • 11. some code smells: ►► duplicate code ►► long method ►► large class ►► combinatorial explosion ►► conditional complexity ►► switch statements ►► indecent exposure
  • 12. Code often starts simple But “grows”: ►► more methods in a class ►► longer methods ►► more if then but if then while x>0 or and etc. ►► more classes, that depends on other classes and becomes more complex
  • 13. Example: a shopping cart ►► implement putting products in the cart ►► start with some pay() method ►► if paypal then..., if iDEAL then... ►► let’s extract a payment interface ►► with several implementations (paypal, iDEAL, etc) ►► mutually exclusive choices each choice is a “strategy” (hurray, our first pattern!)
  • 15. Strategy pattern For instance: different payment possibilities at checkout
  • 16. Replace Conditional Logic with Strategy if ($income <= 10000) { return $income*0.365; } else if ($income <= 30000) { return ($income-10000)*0.2+35600; } else //etc (...) return ($income-60000)*0.02+105600; } // note: mutual exclusive grouping if ($income <= 100000) { $strategy = new InsuranceStrategyLow($income); } else if ($income <= 300000) { $strategy = new InsuranceStrategyMedium($income); } else //etc (...) $strategy = new InsuranceStrategyVeryHigh($income); } return $strategy->calculateInsurance(); http://wiki.jetbrains.net/intellij/Replace_conditional_logic_with_strategy_pattern
  • 17. Strategy When something can be done in several ways, make those ways interchangeable. POSSI- BILITIES c©yepr
  • 18. State example: states of a document ►► a draft doesn’t need a depublish() method ►► a published document doesn’t need a publish() method or states of a shopping-cart ►► while shopping you don’t need a pay() method ►► but you need methods to put product in or out the cart ►► when paid you don’t need a pay() method ►► nor put_product_in_cart()
  • 19. State Let an object show other methods after a change of internal state (as if it changes it’s class). in a.....hick......different state, ....hick....I behave differently....hick..... c© yepr
  • 20. Bridge example: payment and payment providers
  • 21. Bridge Decouple an abstraction from its implementation.c COLA COLA COLA COLA 1 LITER 1 LITER COLA MILK MILK 1 LITER 1 LITER MILK ©yepr
  • 23. Factory method example: different kinds of customers...
  • 24. ...with different kinds of invoices
  • 25. Factory Method Provide an interface for the creation of objects. Allow subclasses to “decide” which class to instantiate. c©yepr
  • 26. Abstract factory example: a Gold customer, cart, invoice, etc.
  • 27. Abstract Factory Povide an interface for creating families of related or dependent objects. A factory for factories. c©yepr
  • 28. Building (complex) objects Example: DI-container Other example: documentbuilder (for tree-like structures): /$domtree = new DOMDocument(‘1.0’, ‘UTF-8’); /* create the root element of the xml tree */ $xmlRoot = $domtree->createElement(“xml”); /* append it to the document created */ $xmlRoot = $domtree->appendChild($xmlRoot); $currentTrack = $domtree->createElement(“track”); $currentTrack = $xmlRoot->appendChild($currentTrack); // etc...
  • 29. Builder Seperate the construction process (how) of a complex object from the concrete representations (what). c©yepr
  • 31. Template Method The skeleton of an algorithm is fixed, but parts can be filled in differently. c©yepr
  • 32. Add behaviour ►► but respect the Open-Closed principle
  • 34. In PHP you can use __call to copy parent methods: public function __call($method, $args) { return call_user_func_array( array($this->decoratedInstance, $method), $args ); } N.B.: Magic functions are magic... but come at a cost!
  • 35. Decorator Add extra functionallity (at runtime), while keeping the interface the same. Matroushka’s... c©yepr
  • 37. Visitor Make a kind of plugin-possibility for methods: in that way methods can be added in runtime. printservice! c©yepr
  • 38. Composite Create a tree structure for part-whole hierarchies. A node is also a (part of a) tree. Recursive: c©yepr
  • 40. Unify interfaces with Adapter: For instance: different payment gateways (PayPal, iDEAL, Hipay, Moneybookers, etc.) Instead of different interfaces refactor to one preferred interface and write adapters for the others
  • 41. Adapter (= Wrapper) Adapt an interface to an expected interface.c©yepr
  • 42. Proxy Provide a surrogate or placeholder for another object to control access to it. c©yepr
  • 43. Facade Provide a general (simpler) interface for a set of interfaces. looks simple c©yepr
  • 45. Observer Notify “subscribers” of changes. WHO? ME ME MENO c©yepr
  • 46. Mediator Layer in between: communication via one object.c©yepr
  • 47. Undo
  • 48. Memento Save and restore the internal state of an object. ME c©yepr
  • 50. Chain of Responsibility Define a method of passing a request among a chain of objects.c©yepr
  • 51. A command is an object to execute 1 method Decoupling (Symfony2) Forms from Entities: http://verraes.net/2013/04/decoupling-symfony2-forms-from-entities/ Chain of Command: Chain of Responsability with Commands Replace Conditional Dispatcher with Command if ($actionName == NEW_WORKSHOP) { //do a lot } else if ($actionName == ALL_WORKSHOPS) { // do a lot of other things } // and many more elseif-statements NewWorkshopHandler, AllWorkshopsHandler, etc.
  • 52. Command Encapsulate a command request in an object.c YOU,DO YOUR TASK! LIGHT OFF LIGHT ON TASKTASK ©yepr
  • 54. Flyweight Use one instance of a class to provide many “virtual” instances. c©yepr
  • 55. PHP: SPL iterators ►► http://www.php.net/manual/en/class.iterator.php ►► http://www.php.net/manual/en/spl.iterators.php Stefan Froelich: ►► http://www.sitepoint.com/using-spl-iterators-1/ ►► http://www.sitepoint.com/using-spl-iterators-2/ Anthony Ferrara video: ►► http://blog.ircmaxell.com/2013/01/todays-programming-with-anthony-vi- deo.html
  • 56. Iterator Enable sequential access to collection elements, without showing the underlying data-structures (array, list, records, etc) nextnext next c©yepr
  • 57. Replace implicit language with Interpreter: search-methods including combinations: ►► belowPriceAvoidingAColor( ) ►► byColorAndBelowPrice( ) ►► byColorSizeAndBelowPrice( ) interpretable expression: $productSpec = new AndSpec( new BelowPriceSpec(9.00), new NotSpec(newColorSpec(WHITE)) ); “You don’t need an Interpreter for complex languages or for really simple ones.” (Joshua Kerievsky)
  • 58. Interpreter Domain -> (little) language -> grammar -> objects (DSL) he means: do this, do that, and after finishing it, go there! HÉ!HÉ! c©yepr
  • 59. Javascript: var Person = function() { // bladibla }; var Customer = function(name) { this.name = name; }; Customer.prototype = new Person(); Prototype in PHP: ►► adding properties is easy ►► adding behaviour is less obvious, but... ►► CLOSURES can help here, with some (dirty) tricks
  • 60. Prototype Make variations on copies of a basic-object. COPY-SERVICE c©yepr
  • 61. Singleton Ensure a class only has one instance, and provide a global point of access to it. Oh, I’m so loooooooonly c©yepr
  • 62. Singleton Ensure a class only has one instance, and provide a global point of access to it. Did anybody say GLOBAL??? Oh, I’m so loooooooonly c BANNED! ©yepr
  • 63. “Every advantage has its disadvantages” (free to Johan Cruyff, Dutch Football Pattern Designer and Ajax-fan...)
  • 65. Classic pattern categories creational, structural and behavioral patterns: ►► creational: object instantiation ►► structural: larger structures of classes or objects ►► behavioral: interaction and distribution of responsibility
  • 66. Other categorisations Loek Bergman (dev. from Rotterdam): ►► transformational ►► transportational ►► translational Anthony Ferrara: ►► Shim : not necessary (for PHP) ►► decompositional: breaking objects apart ►► compositional: making things simpler by assembling http://loekbergman.nl/InsideArchitecture http://blog.ircmaxell.com/2013/09/beyond-design-patterns.html
  • 67. Creational design patterns ►► Factory Method: Allow subclasses to “decide” which class to instantiate. ►► Abstract Factory: Encapsulate a set of analo- gous factories that produce families of objects. ►► Builder: Encapsulate the construction of com- plex objects from their representation; so, the same building process can create various repre- sentations by specifying only type and content. ►► Singleton: Ensure that only a single instance of a class exists and provide a single method for gaining access to it. ►► Prototype: Create an initialized instance for cloning or copying.
  • 68. Factory Method Provide an interface for the creation of objects. Allow subclasses to “decide” which class to instantiate. c©yepr
  • 69. Abstract Factory Povide an interface for creating families of related or dependent objects. A factory for factories. c©yepr
  • 70. Builder Seperate the construction process (how) of a complex object from the concrete representations (what). c©yepr
  • 71. Singleton Ensure a class only has one instance, and provide a global point of access to it. Oh, I’m so loooooooonly c©yepr
  • 72. Singleton Ensure a class only has one instance, and provide a global point of access to it. Did anybody say GLOBAL??? Oh, I’m so loooooooonly c BANNED! ©yepr
  • 73. Prototype Make variations on copies of a basic-object. COPY-SERVICE c©yepr
  • 74. Structural design patterns ●● Adapter: Adapt an interface to an expected interface. ●● Bridge: Decouple an interface from its implementation. ●● Composite: Create a tree structure for part-whole hierarchies. ●● Decorator: Extend functionality dynamically. ●● Facade: Simplify usage by defining a high-level interface. ●● Flyweight: Support fine-grained objects efficiently by sharing. ●● Proxy: Represent an object with another object for access control.
  • 75. Adapter (= Wrapper) Adapt an interface to an expected interface.c©yepr
  • 76. Bridge Decouple an abstraction from its implementation.c COLA COLA COLA COLA 1 LITER 1 LITER COLA MILK MILK 1 LITER 1 LITER MILK ©yepr
  • 77. Composite Create a tree structure for part-whole hierarchies. A node is also a (part of a) tree. Recursive: c©yepr
  • 78. Decorator Add extra functionallity (at runtime), while keeping the interface the same. Matroushka’s... c©yepr
  • 79. Facade Provide a general (simpler) interface for a set of interfaces. looks simple c©yepr
  • 80. Flyweight Use one instance of a class to provide many “virtual” instances. c©yepr
  • 81. Proxy Provide a surrogate or placeholder for another object to control access to it. c©yepr
  • 82. Behavioral design patterns ●● Chain of Responsibility: Define a method of passing a request among a chain of objects. ●● Command: Encapsulate a command request in an object. ●● Interpreter: Allow inclusion of language elements in an appli- cation. ●● Iterator: Enable sequential access to collection elements. ●● Mediator: Define simplified communication between classes. ●● Memento: Save and restore the internal state of an object. ●● Observer: Define a scheme for notifying objects of changes to another object. ●● State: Alter the behavior of an object when its state changes. ●● Strategy: Encapsulate an algorithm inside a class. ●● Template Method: Allow subclasses to redefine the steps of an algorithm. ●● Visitor: Define a new operation on a class without changing it.
  • 83. Command Encapsulate a command request in an object.c YOU,DO YOUR TASK! LIGHT OFF LIGHT ON TASKTASK ©yepr
  • 84. Chain of Responsibility Define a method of passing a request among a chain of objects.c©yepr
  • 85. Interpreter Domain -> (little) language -> grammar -> objects (DSL) he means: do this, do that, and after finishing it, go there! HÉ!HÉ! c©yepr
  • 86. Iterator Enable sequential access to collection elements, without showing the underlying data-structures (array, list, records, etc) nextnext next c©yepr
  • 87. Mediator Layer in between: communication via one object.c©yepr
  • 88. Memento Save and restore the internal state of an object. ME c©yepr
  • 89. Observer Notify “subscribers” of changes. WHO? ME ME MENO c©yepr
  • 90. State Let an object show other methods after a change of internal state (as if it changes it’s class). in a.....hick......different state, ....hick....I behave differently....hick..... c© yepr
  • 91. Strategy When something can be done in several ways, make those ways interchangeable. POSSI- BILITIES c©yepr
  • 92. Template Method The skeleton of an algorithm is fixed, but parts can be filled in differently. c©yepr
  • 93. Visitor Make a kind of plugin-possibility for methods: in that way methods can be added in runtime. printservice! c©yepr
  • 94. Some books GOF: 23 “classical” patterns: classic, The Book fun! good start
  • 96. Fowler: architectural patterns for enterprise applications Fowler: also known from refactoring Kerievsky: refactoring to patterns PEAA & Refactoring
  • 97. Resign Patterns: Ailments of Unsuitable Project-Disoriented Software
  • 98. Questions? Contact info: Herman Peeren herman@yepr.nl © Yepr Design Pattern Illustrations: Nelleke Verhoeff, Red Cheeks Factory, 2010 Creative Commons Public License for noncommercial use http://creativecommons.org/licenses/by-nc/3.0/legalcode