Skip to content

Commit 6b2bf9b

Browse files
committed
init
0 parents  commit 6b2bf9b

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

51 files changed

+4385
-0
lines changed

.gitignore

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
# Created by .ignore support plugin (hsz.mobi)
2+
### Python template
3+
# Byte-compiled / optimized / DLL files
4+
__pycache__/
5+
*.py[cod]
6+
*$py.class
7+
8+
# C extensions
9+
*.so
10+
11+
# Distribution / packaging
12+
.Python
13+
build/
14+
develop-eggs/
15+
dist/
16+
downloads/
17+
eggs/
18+
.eggs/
19+
lib/
20+
lib64/
21+
parts/
22+
sdist/
23+
var/
24+
wheels/
25+
share/python-wheels/
26+
*.egg-info/
27+
.installed.cfg
28+
*.egg
29+
MANIFEST
30+
31+
# PyInstaller
32+
# Usually these files are written by a python script from a template
33+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
34+
*.manifest
35+
*.spec
36+
37+
# Installer logs
38+
pip-log.txt
39+
pip-delete-this-directory.txt
40+
41+
# Unit test / coverage reports
42+
htmlcov/
43+
.tox/
44+
.nox/
45+
.coverage
46+
.coverage.*
47+
.cache
48+
nosetests.xml
49+
coverage.xml
50+
*.cover
51+
*.py,cover
52+
.hypothesis/
53+
.pytest_cache/
54+
cover/
55+
56+
# Translations
57+
*.mo
58+
*.pot
59+
60+
# Django stuff:
61+
*.log
62+
local_settings.py
63+
db.sqlite3
64+
db.sqlite3-journal
65+
66+
# Flask stuff:
67+
instance/
68+
.webassets-cache
69+
70+
# Scrapy stuff:
71+
.scrapy
72+
73+
# Sphinx documentation
74+
docs/_build/
75+
76+
# PyBuilder
77+
.pybuilder/
78+
target/
79+
80+
# Jupyter Notebook
81+
.ipynb_checkpoints
82+
83+
# IPython
84+
profile_default/
85+
ipython_config.py
86+
87+
# pyenv
88+
# For a library or package, you might want to ignore these files since the code is
89+
# intended to run in multiple environments; otherwise, check them in:
90+
# .python-version
91+
92+
# pipenv
93+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
94+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
95+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
96+
# install all needed dependencies.
97+
#Pipfile.lock
98+
99+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
100+
__pypackages__/
101+
102+
# Celery stuff
103+
celerybeat-schedule
104+
celerybeat.pid
105+
106+
# SageMath parsed files
107+
*.sage.py
108+
109+
# Environments
110+
.env
111+
.venv
112+
env/
113+
venv/
114+
ENV/
115+
env.bak/
116+
venv.bak/
117+
118+
# Spyder project settings
119+
.spyderproject
120+
.spyproject
121+
122+
# Rope project settings
123+
.ropeproject
124+
125+
# mkdocs documentation
126+
/site
127+
128+
# mypy
129+
.mypy_cache/
130+
.dmypy.json
131+
dmypy.json
132+
133+
# Pyre type checker
134+
.pyre/
135+
136+
# pytype static type analyzer
137+
.pytype/
138+
139+
# Cython debug symbols
140+
cython_debug/
141+
142+
### Example user template template
143+
### Example user template
144+
145+
# IntelliJ project files
146+
.idea
147+
*.iml
148+
out
149+
gen

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Паттерны проектирования

behavioral/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Поведенческие паттерны

behavioral/chain_of_responsibility.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
handlers = []
2+
3+
4+
def car_handler(func):
5+
handlers.append(func)
6+
return func
7+
8+
9+
class Car:
10+
def __init__(self):
11+
self.name = None
12+
self.km = 11100
13+
self.fuel = 5
14+
self.oil = 5
15+
16+
17+
@car_handler
18+
def handle_fuel(car):
19+
if car.fuel < 10:
20+
print("added fuel")
21+
car.fuel = 100
22+
23+
24+
@car_handler
25+
def handle_km(car):
26+
if car.km > 10000:
27+
print("made a car test.")
28+
car.km = 0
29+
30+
31+
@car_handler
32+
def handle_oil(car):
33+
if car.oil < 10:
34+
print("Added oil")
35+
car.oil = 100
36+
37+
38+
class Garage:
39+
def __init__(self, handlers=[]):
40+
self.handlers = handlers
41+
42+
def add_handler(self, handler):
43+
self.handlers.append(handler)
44+
45+
def handle_car(self, car):
46+
for handler in self.handlers:
47+
handler(car)
48+
49+
50+
if __name__ == '__main__':
51+
garage = Garage(handlers)
52+
car = Car()
53+
garage.handle_car(car)
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
from __future__ import annotations
2+
from abc import ABC, abstractmethod
3+
from typing import Any, Optional
4+
5+
6+
class Handler(ABC):
7+
"""
8+
Интерфейс Обработчика объявляет метод построения цепочки обработчиков. Он
9+
также объявляет метод для выполнения запроса.
10+
"""
11+
12+
@abstractmethod
13+
def set_next(self, handler: Handler) -> Handler:
14+
pass
15+
16+
@abstractmethod
17+
def handle(self, request) -> Optional[str]:
18+
pass
19+
20+
21+
class AbstractHandler(Handler):
22+
"""
23+
Поведение цепочки по умолчанию может быть реализовано внутри базового класса
24+
обработчика.
25+
"""
26+
27+
_next_handler: Handler = None
28+
29+
def set_next(self, handler: Handler) -> Handler:
30+
self._next_handler = handler
31+
# Возврат обработчика отсюда позволит связать обработчики простым
32+
# способом, вот так:
33+
# monkey.set_next(squirrel).set_next(dog)
34+
return handler
35+
36+
@abstractmethod
37+
def handle(self, request: Any) -> str:
38+
if self._next_handler:
39+
return self._next_handler.handle(request)
40+
41+
return None
42+
43+
44+
"""
45+
Все Конкретные Обработчики либо обрабатывают запрос, либо передают его
46+
следующему обработчику в цепочке.
47+
"""
48+
49+
50+
class MonkeyHandler(AbstractHandler):
51+
def handle(self, request: Any) -> str:
52+
if request == "Banana":
53+
return f"Monkey: I'll eat the {request}"
54+
else:
55+
return super().handle(request)
56+
57+
58+
class SquirrelHandler(AbstractHandler):
59+
def handle(self, request: Any) -> str:
60+
if request == "Nut":
61+
return f"Squirrel: I'll eat the {request}"
62+
else:
63+
return super().handle(request)
64+
65+
66+
class DogHandler(AbstractHandler):
67+
def handle(self, request: Any) -> str:
68+
if request == "MeatBall":
69+
return f"Dog: I'll eat the {request}"
70+
else:
71+
return super().handle(request)
72+
73+
74+
def client_code(handler: Handler) -> None:
75+
"""
76+
Обычно клиентский код приспособлен для работы с единственным обработчиком. В
77+
большинстве случаев клиенту даже неизвестно, что этот обработчик является
78+
частью цепочки.
79+
"""
80+
81+
for food in ["Nut", "Banana", "Cup of coffee"]:
82+
print(f"\nClient: Who wants a {food}?")
83+
result = handler.handle(food)
84+
if result:
85+
print(f" {result}", end="")
86+
else:
87+
print(f" {food} was left untouched.", end="")
88+
89+
90+
if __name__ == "__main__":
91+
monkey = MonkeyHandler()
92+
squirrel = SquirrelHandler()
93+
dog = DogHandler()
94+
95+
monkey.set_next(squirrel).set_next(dog)
96+
97+
# Клиент должен иметь возможность отправлять запрос любому обработчику, а не
98+
# только первому в цепочке.
99+
print("Chain: Monkey > Squirrel > Dog")
100+
client_code(monkey)
101+
print("\n")
102+
103+
print("Subchain: Squirrel > Dog")
104+
client_code(squirrel)

0 commit comments

Comments
 (0)