|
1
|
|
|
from abc import ABC, abstractmethod |
|
2
|
|
|
|
|
3
|
|
|
|
|
4
|
|
|
__all__ = ['RealSubject', 'Proxy'] |
|
5
|
|
|
|
|
6
|
|
|
|
|
7
|
|
|
class Subject(ABC): |
|
8
|
|
|
""" |
|
9
|
|
|
The Subject interface declares common operations for both RealSubject and |
|
10
|
|
|
the Proxy. As long as the client works with RealSubject using this |
|
11
|
|
|
interface, you'll be able to pass it a proxy instead of a real subject. |
|
12
|
|
|
""" |
|
13
|
|
|
|
|
14
|
|
|
@abstractmethod |
|
15
|
|
|
def request(self, *args, **kwargs) -> None: |
|
16
|
|
|
raise NotImplementedError |
|
17
|
|
|
|
|
18
|
|
|
|
|
19
|
|
|
class RealSubject(Subject): |
|
20
|
|
|
""" |
|
21
|
|
|
The RealSubject contains some core business logic. Usually, RealSubjects are |
|
22
|
|
|
capable of doing some useful work which may also be very slow or sensitive - |
|
23
|
|
|
e.g. correcting input data. A Proxy can solve these issues without any |
|
24
|
|
|
changes to the RealSubject's code. |
|
25
|
|
|
""" |
|
26
|
|
|
|
|
27
|
|
|
def request(self, *args, **kwargs) -> None: |
|
28
|
|
|
raise NotImplementedError |
|
29
|
|
|
|
|
30
|
|
|
|
|
31
|
|
|
# TODO use generic typers to define RealSubject at runtime |
|
32
|
|
|
# then the client code will not have to overide the RealSubject |
|
33
|
|
|
class Proxy(Subject): |
|
34
|
|
|
""" |
|
35
|
|
|
The Proxy has an interface identical to the RealSubject. |
|
36
|
|
|
""" |
|
37
|
|
|
|
|
38
|
|
|
def __init__(self, real_subject: RealSubject) -> None: |
|
39
|
|
|
self._real_subject = real_subject |
|
40
|
|
|
|
|
41
|
|
|
def request(self, *args, **kwargs) -> None: |
|
42
|
|
|
""" |
|
43
|
|
|
The most common applications of the Proxy pattern are lazy loading, |
|
44
|
|
|
caching, controlling the access, logging, etc. A Proxy can perform one |
|
45
|
|
|
of these things and then, depending on the result, pass the execution to |
|
46
|
|
|
the same method in a linked RealSubject object. |
|
47
|
|
|
""" |
|
48
|
|
|
return self._real_subject.request(*args, **kwargs) |
|
49
|
|
|
|