Behavioural patterns
The eleven behavioural patterns of the GoF catalogue: Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method and Visitor. Intent, participants and code examples.
- 33 cards
- 3 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
A few cards from the deck
Chain of Responsibility: what is it?
Show the answer
Behavioural pattern that passes a request along a series of handlers until one of them deals with it.
The sender does not know who will answer. Each handler deals with the request or passes it on, like a refund request that goes up from approver to approver.
What does this program print?
```python
class Sujet:
def __init__(self):
self.abonnes = []
def notifier(self, msg):
for a in list(self.abonnes):
a(msg)
s = Sujet()
a = lambda m: print("A", m)
b = lambda m: print("B", m)
s.abonnes += [a, b]
s.notifier("un")
s.abonnes.remove(a)
s.notifier("deux")`A un,B un,B deuxA un,B un,A deuxA un,B un,A deux,B deuxB un,A un,B deux
Show the answer
A un,B un,B deuxThe first call notifies subscribers in registration order, A then B. After A is removed, only B is notified for "deux". Output run under Python.
In Observer, the … keeps the list of its subscribers and calls their update method at each state change.
Show the answer
In Observer, the subject keeps the list of its subscribers and calls their update method at each state change.
The subject only knows its subscribers through an interface: they can be added or removed without touching its code.
Command: what is it?
Show the answer
Behavioural pattern that turns a request into an object, so it can be stored, queued, undone or replayed.
The command object carries the action and its parameters, often with
execute()andundo(). A stack of commands gives an editor its history and its undo.Which approver approves a request of 800 euros?
```python
class Valideur:
def __init__(self, nom, plafond, suivant=None):
self.nom, self.plafond, self.suivant = nom, plafond, suivant
def traiter(self, montant):
if montant <= self.plafond:
return self.nom
return self.suivant.traiter(montant)
chaine = Valideur("chef", 500, Valideur("directeur", 2000, Valideur("PDG", 10000)))
print(chaine.traiter(800))`chefdirecteurPDGchefthendirecteur
Show the answer
directeur800 exceeds the chief's limit (500): the request goes to the next link, the director (2000), who handles it and stops the chain. The CEO is never called.