-
-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathproxy_concept.py
58 lines (45 loc) · 1.52 KB
/
proxy_concept.py
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
# pylint: disable=too-few-public-methods
# pylint: disable=arguments-differ
"A Proxy Concept Example"
from abc import ABCMeta, abstractmethod
class ISubject(metaclass=ABCMeta):
"An interface implemented by both the Proxy and Real Subject"
@staticmethod
@abstractmethod
def request():
"A method to implement"
class RealSubject(ISubject):
"The actual real object that the proxy is representing"
def __init__(self):
# hypothetically enormous amounts of data
self.enormous_data = [1, 2, 3]
def request(self):
return self.enormous_data
class Proxy(ISubject):
"""
The proxy. In this case the proxy will act as a cache for
`enormous_data` and only populate the enormous_data when it
is actually necessary
"""
def __init__(self):
self.enormous_data = []
self.real_subject = RealSubject()
def request(self):
"""
Using the proxy as a cache, and loading data into it only if
it is needed
"""
if not self.enormous_data:
print("pulling data from RealSubject")
self.enormous_data = self.real_subject.request()
return self.enormous_data
print("pulling data from Proxy cache")
return self.enormous_data
# The Client
SUBJECT = Proxy()
# use SUBJECT
print(id(SUBJECT))
# load the enormous amounts of data because now we want to show it.
print(SUBJECT.request())
# show the data again, but this time it retrieves it from the local cache
print(SUBJECT.request())