-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathexample.py
More file actions
79 lines (52 loc) · 1.74 KB
/
Copy pathexample.py
File metadata and controls
79 lines (52 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
# SOURCE: Design Patterns: Proxy - Заместитель
# SOURCE: https://ru.wikipedia.org/wiki/Заместитель_(шаблон_проектирования)
class IMath:
"""Интерфейс для прокси и реального субъекта"""
def add(self, x, y):
raise NotImplementedError()
def sub(self, x, y):
raise NotImplementedError()
def mul(self, x, y):
raise NotImplementedError()
def div(self, x, y):
raise NotImplementedError()
class Math(IMath):
"""Реальный субъект"""
def add(self, x, y):
return x + y
def sub(self, x, y):
return x - y
def mul(self, x, y):
return x * y
def div(self, x, y):
return x / y
class MathProxy(IMath):
"""Прокси"""
def __init__(self) -> None:
self.math = None
# Быстрые операции - не требуют реального субъекта
def add(self, x, y):
return x + y
def sub(self, x, y):
return x - y
# Медленная операция - требует создания реального субъекта
def mul(self, x, y):
if not self.math:
self.math = Math()
return self.math.mul(x, y)
def div(self, x, y):
if y == 0:
return float("inf") # Вернуть positive infinity
if not self.math:
self.math = Math()
return self.math.div(x, y)
if __name__ == "__main__":
p = MathProxy()
x, y = 4, 2
print("4 + 2 =", p.add(x, y))
print("4 - 2 =", p.sub(x, y))
print("4 * 2 =", p.mul(x, y))
print("4 / 2 =", p.div(x, y))