design-patterns/behavioral/chain_responsibility/main.py
Ruidy c8cc1f47b8
Observer (#20)
* doc: create package & update general TOCs

* doc: add documentation

* add code example

* reformat using black
2020-10-06 08:25:18 +02:00

39 lines
1 KiB
Python

from behavioral.chain_responsibility.concrete_handlers import (
MonkeyHandler,
SquirrelHandler,
DogHandler,
)
from behavioral.chain_responsibility.handler import Handler
def client_code(handler: Handler):
"""
The client code is usually suited to work with a single handler. In most
cases, it is not even aware that the handler is part of a chain.
"""
for food in ["Nut", "Banana", "Cup of coffee"]:
print(f"\nClient: Who wants a {food}?")
result = handler.handle(food)
if result:
print(f" {result}", end="")
else:
print(f" {food} was left untouched.", end="")
if __name__ == "__main__":
monkey = MonkeyHandler()
squirrel = SquirrelHandler()
dog = DogHandler()
monkey.set_next(squirrel).set_next(dog)
# The client should be able to send a request to any handler, not just the
# first one in the chain.
print("Chain: Monkey > Squirrel > Dog")
client_code(monkey)
print("\n")
print("Subchain: Squirrel > Dog")
client_code(squirrel)