Skip to content

Instantly share code, notes, and snippets.

@tonvanbart
Last active March 28, 2021 13:56
Show Gist options
  • Save tonvanbart/44dcf13f1be90410e71d8a888e69ec8e to your computer and use it in GitHub Desktop.
Save tonvanbart/44dcf13f1be90410e71d8a888e69ec8e to your computer and use it in GitHub Desktop.
Example Python GoF proxy
from abc import ABC, abstractmethod
class ProxySubject(ABC):
"""
The interface we will use in our proxy and subject.
"""
@abstractmethod
def do_stuff(self, arg):
pass
@abstractmethod
def say_something(self) -> str:
pass
def not_abstract(self) -> str:
return "default"
class Concrete(ProxySubject):
"""
Base concrete implementstion
"""
def do_stuff(self, arg):
print("Concrete doing stuff with", arg)
def say_something(self) -> str:
return "hello"
class Proxy(ProxySubject):
"""
The proxy which proxies any instance of the interface (so proxies can be chained)
"""
def __init__(self, delegate: ProxySubject):
self._delegate = delegate
def do_stuff(self, arg):
print("here is the proxy calling the delegate for", arg)
self._delegate.do_stuff(arg)
def say_something(self) -> str:
return self._delegate.say_something().upper()
def not_abstract(self) -> str:
return self._delegate.not_abstract()[::-1]
if __name__ == "__main__":
concrete = Concrete()
proxy = Proxy(concrete)
proxy.do_stuff("foo")
print("Calling the proxy:", proxy.say_something())
print("calling not_abstract:", proxy.not_abstract())
proxy2 = Proxy(proxy)
print("calling proxy chain:", proxy2.not_abstract())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment