formations/python/python2/formation/DesignPatterns.txt

95 lines
1.8 KiB
Plaintext

Les design patterns
=====================
Les design patterns **ne sont pas** indépendants du langage.
Ils dépendent de l'implémentation.
Le duck typing
-------------------
En python, le duck typing est une forme extreme de programmation par interface.
Ne pas hériter dans des directions fausse
exemple : une voiture ne peut hériter d'un moteur, parce que un moteur n'est pas une voiture.
hold or wrap ?
--------------
**hold**::
O.S.method()
Cela induit un couplage fort (cf la loi de Demeter)
.. important:: law of Demeter : never more than one dot.
wrap : a hold by private name, with a::
self.S.method()
Ou bien une méthode getattr::
__getattr__()
Gets coupling right.
wrapper can restrict, inheritance cannot restrict
--------------------------------------------------
::
class RestrictingWrapper(object):
def __init__(self, w, block):
self._w = w
self._block = block
def __getattr__(self, n):
if n in self._block:
raise AttributeError, n
return getattr(self._w, n)
Pattern de création : singleton
-------------------------------
# utiliser un module au lieu d'une classe
in `toto.py`::
class Toto()
toto = Toto()
in another module::
from toto import toto
la factory
--------------
::
def load(pkg, obj):
m = __import__(pkg, {}, {}, [obj])
return getattr(m, obj)
cls = load('p1.p2.p3', 'c4')
template method (self delegation)
---------------------------------
# Abstract base class::
def OrganiseMethod()
def org_method():
def do_this()
def do_that()
def Concrete(OrganiseMethod)
def do_this(): ...
def do_that(): ...
il est préférable de lever une NotImplementedError, ce qui revient à faire
une classe abstraite.