Skip to content

Instantly share code, notes, and snippets.

@simongarisch
Created October 16, 2019 22:13
Show Gist options
  • Save simongarisch/8974dd8003b7eba8cb678f887d2c017b to your computer and use it in GitHub Desktop.
Save simongarisch/8974dd8003b7eba8cb678f887d2c017b to your computer and use it in GitHub Desktop.
Python structural patterns - proxy
# The proxy pattern allows us to perform some action, usually a check, before accessing an object.
from abc import ABC, abstractmethod
# define some interface
class Passwords(ABC):
@abstractmethod
def get_master_password(self):
raise NotImplementedError
# and implementations of this
class SimonsPasswords(Passwords):
def get_master_password(self):
return "Wubba lubba dub dub"
class PasswordsProxy(Passwords):
""" Run a check to see if the user is Simon.
If the user is Simon then return password text,
otherwise hide the password.
"""
def __init__(self, user):
self.user = user
self.passwords = SimonsPasswords()
def get_master_password(self):
password = self.passwords.get_master_password()
if self.user.lower() == "simon":
return password
else:
return "*" * len(password)
proxy = PasswordsProxy(user="Bob")
print(proxy.get_master_password()) # *******************
proxy = PasswordsProxy(user="Simon")
print(proxy.get_master_password()) # Wubba lubba dub dub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment