Design patterns illustrated 010PHP

Preview:

DESCRIPTION

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.

Citation preview

Design Patterns illustrated

Herman Peeren, February 13, 2014(Design Patterns illustrations: Nelleke Verhoeff, 2010)

TöröööBy Laurent Steinmayer

010PHP

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

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

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 MethodProvide an interface for the creation of objects.Allow subclasses to “decide” which class to instantiate.

yep

r

Example: different kinds of customers...

...with different kinds of invoices

Abstract FactoryPovide an interface for creating families of related or dependent objects. A factory for factories.

yep

r

Example: a Gold customer, cart, invoice, etc.

BuilderSeperate the construction process (how) of a complex object from the concrete representations (what).

yep

r

Example: querybuilder:

Example: documentbuilder (for tree-like structures):

$qb->select(‘u’) ->from(‘User’, ‘u’) ->where(‘u.id = ?1’) ->orderBy(‘u.name’, ‘ASC’);

/$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...

SingletonEnsure a class only has one instance, and provide a global point of access to it.

Oh, I’m soloooooooonly

c© ye

pr

SingletonEnsure a class only has one instance, and provide a global point of access to it. Did anybody say GLOBAL???

Oh, I’m soloooooooonly

c BANN

ED!

© y

epr

“Every advantage

has its disadvantages”

(free to Johan Cruyff, Dutch Football Pattern Designer and Ajax-fan...)

PrototypeMake variations on copies of a basic-object.

COPY-SERVICE

yep

r

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

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.

yep

r

Unify interfaces with Adapter:For instance: different payment gateways (PayPal, iDEAL, Hipay, Moneybookers, etc.)

Instead of different interfaces refactor to

one preferred interfaceand write adapters for the others

BridgeDecouple an abstraction from its implementation.

c

COLA

COLA

COLA

COLA

1 LITER

1 LITER

COLA

MILK

MILK

1 LITER

1 LITER

MILK

© y

epr

Example: payment and payment providers

CompositeCreate a tree structure for part-whole hierarchies. A node is also a (part of a) tree. Recursive:

yep

r

DecoratorAdd extra functionallity (at runtime), while keeping the interface the same. Matroushka’s...

c© ye

pr

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!

FacadeProvide a general (simpler) interface for a set of interfaces.

lookssimple

yep

r

FlyweightUse one instance of a class to provide many “virtual” instances.

yep

r

ProxyProvide a surrogate or placeholder for another object to control access to it.

yep

r

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.

CommandEncapsulate a command request in an object.

c

YOU,DO YOURTASK!

LIGHTOFF

LIGHTON

TASKTASK

© y

epr

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 Commandif ($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.

Chain of ResponsibilityDefine a method of passing a request among a chain of objects.

c© ye

pr

InterpreterDomain -> (little) language -> grammar -> objects (DSL)

he means:do this, do that,

and after finishing it, go there!

HÉ!HÉ!

yep

r

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)

IteratorEnable sequential access to collection elements, without showing the underlying data-structures (array, list, records, etc)

nextnext

next

yep

r

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

MediatorLayer in between: communication via one object.

yep

r

MementoSave and restore the internal state of an object.

ME

c© ye

pr

ObserverNotify “subscribers” of changes.

WHO?

ME

ME

MENO

yep

r

StateLet 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

StrategyWhen something can be done in several ways, make those ways interchangeable.

POSSI-BILITIES

yep

r

Strategy

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

Template MethodThe skeleton of an algorithm is fixed, but parts can be filled in differently.

yep

r

VisitorMake a kind of plugin-possibility for methods: in that way methods can be added in runtime.

printservice!

yep

r

Move Accumulation to Visitor

Some booksGOF: 23 “classical” patterns:

classic, The Book

fun!

good start

Dec. 2013Simple

Febr. 2013Selection

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 Peerenherman@yepr.nl

© YeprDesign Pattern Illustrations: Nelleke Verhoeff, Red Cheeks Factory, 2010 Creative Commons Public License for noncommercial use http://creativecommons.org/licenses/by-nc/3.0/legalcode