| Total Complexity | 4 |
| Total Lines | 57 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | """Proxy structural software pattern. |
||
| 2 | |||
| 3 | This module contains boiler-plate code to supply the Proxy structural software |
||
| 4 | design pattern, to the client code.""" |
||
| 5 | |||
| 6 | from abc import ABC |
||
| 7 | from typing import Generic, TypeVar |
||
| 8 | |||
| 9 | T = TypeVar('T') |
||
| 10 | |||
| 11 | |||
| 12 | __all__ = ['Proxy'] |
||
| 13 | |||
| 14 | |||
| 15 | class ProxySubjectInterface(ABC): |
||
| 16 | """Proxy Subject interface holding the important 'request' operation. |
||
| 17 | |||
| 18 | Declares common operations for both ProxySubject and |
||
| 19 | the Proxy. As long as the client uses ProxySubject's interface, a proxy can |
||
| 20 | be passed pass to it, instead of a real subject. |
||
| 21 | """ |
||
| 22 | |||
| 23 | |||
| 24 | class Proxy(ProxySubjectInterface, Generic[T]): |
||
| 25 | """ |
||
| 26 | The Proxy has an interface identical to the ProxySubject. |
||
| 27 | |||
| 28 | Example: |
||
| 29 | |||
| 30 | >>> from software_patterns import Proxy |
||
| 31 | >>> class PlusTen(Proxy): |
||
| 32 | ... def __call__(self, x: int): |
||
| 33 | ... result = self._proxy_subject(x + 10) |
||
| 34 | ... return result |
||
| 35 | |||
| 36 | >>> def plus_one(x: int): |
||
| 37 | ... return x + 1 |
||
| 38 | >>> plus_one(2) |
||
| 39 | 3 |
||
| 40 | |||
| 41 | >>> proxy = PlusTen(plus_one) |
||
| 42 | >>> proxy(2) |
||
| 43 | 13 |
||
| 44 | """ |
||
| 45 | |||
| 46 | def __init__(self, runtime_proxy: T): |
||
| 47 | self._proxy_subject = runtime_proxy |
||
| 48 | |||
| 49 | def __getattr__(self, name: str): |
||
| 50 | return getattr(self._proxy_subject, name) |
||
| 51 | |||
| 52 | def __str__(self): |
||
| 53 | return str(self._proxy_subject) |
||
| 54 | |||
| 55 | def __hash__(self): |
||
| 56 | return hash(self._proxy_subject) |
||
| 57 |