All 'classic' 23 GOF Design Patterns, illustrated by Nelleke Verhoeff (Red Cheeks Factory). Trying to show the essence of each Design Pattern, with some examples from PHP.
Second version of my Design Patterns presentation. This presentation was held February 13, 2014 at the 010PHP meeting in Rotterdam. Presentation was in Dutch.
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
11. some code smells:
►►duplicate code
►►long method
►►large class
►►combinatorial explosion
►►conditional complexity
►►switch statements
►►indecent exposure
12. Classic pattern categories
creational, structural and behavioral patterns:
►►creational: object instantiation
►►structural: larger structures of classes or objects
►►behavioral: interaction and distribution of responsibility
13. 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
14. 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.
21. Example: querybuilder:
$qb->select(‘u’)
->from(‘User’, ‘u’)
->where(‘u.id = ?1’)
->orderBy(‘u.name’, ‘ASC’);
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...
26. 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
27. 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 fficiently by sharing.
e
●● Proxy: Represent an object with another object for access control.
29. 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
35. 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!
39. 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 application.
●● 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.
41. 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.
44. 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)