17.12.2012 Views

Programmation PYTHON - Zenk - Security - Repository

Programmation PYTHON - Zenk - Security - Repository

Programmation PYTHON - Zenk - Security - Repository

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Programmation</strong> orientée objet<br />

CHAPITRE 14<br />

La méthode __add__() du handler est relativement puissante ici, car elle permet de<br />

construire très simplement la chaîne : quand un handler B est additionné à un handler<br />

A, A parcourt la chaîne en partant de son voisin de droite pour aller placer le<br />

handler B en bout de chaîne.<br />

Le chaînage des appels se fait par le biais de l’exception NotImplementedError :<br />

chaque handler qui ne sait pas gérer les données qui lui sont envoyées lève l’exception<br />

pour appeler le suivant. Si aucun handler ne peut gérer les données, l’exception sort<br />

de la chaîne.<br />

Dans l’exemple ci-dessous, chaque handler est spécialisé dans un type de données.<br />

Utilisation de Chain of responsibility<br />

class StringHandler(Handler):<br />

"""handler de string"""<br />

def _handle(self, data):<br />

if isinstance(data, str):<br />

return data.lower()<br />

else:<br />

raise NotImplementedError<br />

class IntHandler(Handler):<br />

"""handler de int"""<br />

def _handle(self, data):<br />

if isinstance(data, int):<br />

return data * 2<br />

else:<br />

raise NotImplementedError<br />

class UnicodeHandler(Handler):<br />

"""handler de unicode"""<br />

def _handle(self, data):<br />

if isinstance(data, unicode):<br />

return u'%s (unicode)' % data<br />

else:<br />

raise NotImplementedError<br />

calculator = Director(StringHandler() + IntHandler() + UnicodeHandler())<br />

print(calculator(1))<br />

print(calculator(u'test'))<br />

print(calculator('test'))<br />

print(calculator(object()))<br />

[...]<br />

[tziade@Tarek Desktop]$ python chain_of_responsibility.py<br />

2<br />

515

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!