SlideShare a Scribd company logo
1 of 98
Download to read offline
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

What's hot

Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascriptUsman Mehmood
 
P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptSanthosh Kumar Srinivasan
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practicesManav Gupta
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS ImplimentationUsman Mehmood
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript ProgrammingSehwan Noh
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPTkishu0005
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHPVibrant Technologies & Computers
 
Java oops and fundamentals
Java oops and fundamentalsJava oops and fundamentals
Java oops and fundamentalsjavaease
 
Model Manipulation Using Embedded DSLs in Scala
Model Manipulation Using Embedded DSLs in ScalaModel Manipulation Using Embedded DSLs in Scala
Model Manipulation Using Embedded DSLs in ScalaFilip Krikava
 

What's hot (20)

Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in Javascript
 
Js: master prototypes
Js: master prototypesJs: master prototypes
Js: master prototypes
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS Implimentation
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
OOPs in Java
OOPs in JavaOOPs in Java
OOPs in Java
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
JAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - MultithreadingJAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - Multithreading
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
Java oops and fundamentals
Java oops and fundamentalsJava oops and fundamentals
Java oops and fundamentals
 
Patterns In-Javascript
Patterns In-JavascriptPatterns In-Javascript
Patterns In-Javascript
 
Inheritance Mixins & Traits
Inheritance Mixins & TraitsInheritance Mixins & Traits
Inheritance Mixins & Traits
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
Model Manipulation Using Embedded DSLs in Scala
Model Manipulation Using Embedded DSLs in ScalaModel Manipulation Using Embedded DSLs in Scala
Model Manipulation Using Embedded DSLs in Scala
 
OOPS in Java
OOPS in JavaOOPS in Java
OOPS in Java
 

Viewers also liked

Lesson 13 demonstrative pronouns
Lesson 13 demonstrative pronounsLesson 13 demonstrative pronouns
Lesson 13 demonstrative pronounsJohn Acuña
 
Padroes De Projeto
Padroes De ProjetoPadroes De Projeto
Padroes De Projetoejdn1
 
Exemplos de Design Patterns em Java
Exemplos de Design Patterns em JavaExemplos de Design Patterns em Java
Exemplos de Design Patterns em Javaalexmacedo
 
Design Patterns For 70% Of Programmers In The World
Design Patterns For 70% Of Programmers In The WorldDesign Patterns For 70% Of Programmers In The World
Design Patterns For 70% Of Programmers In The WorldSaurabh Moody
 

Viewers also liked (9)

Palestra ASP.NET MVC
Palestra ASP.NET MVCPalestra ASP.NET MVC
Palestra ASP.NET MVC
 
Design patterns - Strategy Pattern
Design patterns - Strategy PatternDesign patterns - Strategy Pattern
Design patterns - Strategy Pattern
 
Hello world e4 application part 5
Hello world e4 application   part 5Hello world e4 application   part 5
Hello world e4 application part 5
 
Lesson 13 demonstrative pronouns
Lesson 13 demonstrative pronounsLesson 13 demonstrative pronouns
Lesson 13 demonstrative pronouns
 
Mobile games
Mobile gamesMobile games
Mobile games
 
Padroes De Projeto
Padroes De ProjetoPadroes De Projeto
Padroes De Projeto
 
Exemplos de Design Patterns em Java
Exemplos de Design Patterns em JavaExemplos de Design Patterns em Java
Exemplos de Design Patterns em Java
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
Design Patterns For 70% Of Programmers In The World
Design Patterns For 70% Of Programmers In The WorldDesign Patterns For 70% Of Programmers In The World
Design Patterns For 70% Of Programmers In The World
 

Similar to Design patterns illustrated-2015-03

Designpatterns illustrated
Designpatterns illustratedDesignpatterns illustrated
Designpatterns illustratedNhat Vo Van
 
Reviewing OOP Design patterns
Reviewing OOP Design patternsReviewing OOP Design patterns
Reviewing OOP Design patternsOlivier Bacs
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternNishith Shukla
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsLalit Kale
 
Java Programming
Java ProgrammingJava Programming
Java ProgrammingTracy Clark
 
Design Patterns in Cocoa Touch
Design Patterns in Cocoa TouchDesign Patterns in Cocoa Touch
Design Patterns in Cocoa TouchEliah Nikans
 
27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examplesQuang Suma
 
Dependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPDependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPmtoppa
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principlesdeonpmeyer
 
Design patterns in brief
Design patterns in briefDesign patterns in brief
Design patterns in briefDUONG Trong Tan
 
Framework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users GroupFramework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users Groupbrada
 
Developing maintainable Cordova applications
Developing maintainable Cordova applicationsDeveloping maintainable Cordova applications
Developing maintainable Cordova applicationsIvano Malavolta
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptAyush Sharma
 
How to design an application correctly ?
How to design an application correctly ?How to design an application correctly ?
How to design an application correctly ?Guillaume AGIS
 

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

Introduction to Design Patterns
Introduction to Design PatternsIntroduction to Design Patterns
Introduction to Design Patterns
 
Designpatterns illustrated
Designpatterns illustratedDesignpatterns illustrated
Designpatterns illustrated
 
Reviewing OOP Design patterns
Reviewing OOP Design patternsReviewing OOP Design patterns
Reviewing OOP Design patterns
 
Gdd pydp
Gdd pydpGdd pydp
Gdd pydp
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Design Patterns in Cocoa Touch
Design Patterns in Cocoa TouchDesign Patterns in Cocoa Touch
Design Patterns in Cocoa Touch
 
27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Dependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPDependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHP
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
 
Design patterns in brief
Design patterns in briefDesign patterns in brief
Design patterns in brief
 
Framework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users GroupFramework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users Group
 
Developing maintainable Cordova applications
Developing maintainable Cordova applicationsDeveloping maintainable Cordova applications
Developing maintainable Cordova applications
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
.NET for hackers
.NET for hackers.NET for hackers
.NET for hackers
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
 
Solid OOPS
Solid OOPSSolid OOPS
Solid OOPS
 
How to design an application correctly ?
How to design an application correctly ?How to design an application correctly ?
How to design an application correctly ?
 

More from Herman Peeren

ProjectionalForms-2023-11-14.pdf
ProjectionalForms-2023-11-14.pdfProjectionalForms-2023-11-14.pdf
ProjectionalForms-2023-11-14.pdfHerman Peeren
 
ExtensionGenerator-JoomlaDagen2023-slides.pdf
ExtensionGenerator-JoomlaDagen2023-slides.pdfExtensionGenerator-JoomlaDagen2023-slides.pdf
ExtensionGenerator-JoomlaDagen2023-slides.pdfHerman Peeren
 
Programmeren, talen en het begrijpen van de wereld
Programmeren, talen en het begrijpen van de wereldProgrammeren, talen en het begrijpen van de wereld
Programmeren, talen en het begrijpen van de wereldHerman Peeren
 
Improve our PHP code with ideas from Functional Programming
Improve our PHP code with ideas from Functional ProgrammingImprove our PHP code with ideas from Functional Programming
Improve our PHP code with ideas from Functional ProgrammingHerman Peeren
 
DCI DDD-BE April 2015
DCI DDD-BE April 2015DCI DDD-BE April 2015
DCI DDD-BE April 2015Herman Peeren
 
Next Generation Joomla!
Next Generation Joomla!Next Generation Joomla!
Next Generation Joomla!Herman Peeren
 
Behat, Behavioral Driven Development (BDD) in PHP
Behat, Behavioral Driven Development (BDD) in PHPBehat, Behavioral Driven Development (BDD) in PHP
Behat, Behavioral Driven Development (BDD) in PHPHerman Peeren
 
Print, geen kunst aan
Print, geen kunst aanPrint, geen kunst aan
Print, geen kunst aanHerman Peeren
 
Jooctrine - Doctrine ORM in Joomla!
Jooctrine - Doctrine ORM in Joomla!Jooctrine - Doctrine ORM in Joomla!
Jooctrine - Doctrine ORM in Joomla!Herman Peeren
 
#jd12nl Joomla 2.5 extensies
#jd12nl Joomla 2.5 extensies#jd12nl Joomla 2.5 extensies
#jd12nl Joomla 2.5 extensiesHerman Peeren
 
Jug010 120320-templates
Jug010 120320-templatesJug010 120320-templates
Jug010 120320-templatesHerman Peeren
 
Joomla2.0 architecture
Joomla2.0 architectureJoomla2.0 architecture
Joomla2.0 architectureHerman Peeren
 
Webservices: connecting Joomla! with other programs.
Webservices: connecting Joomla! with other programs.Webservices: connecting Joomla! with other programs.
Webservices: connecting Joomla! with other programs.Herman Peeren
 
Commercial gpljoomla
Commercial gpljoomlaCommercial gpljoomla
Commercial gpljoomlaHerman Peeren
 
Flash templates for Joomla!
Flash templates for Joomla!Flash templates for Joomla!
Flash templates for Joomla!Herman Peeren
 

More from Herman Peeren (19)

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

Recently uploaded

Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 

Recently uploaded (20)

Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 

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