Last active
August 28, 2016 14:38
-
-
Save worldofprasanna/24f8ee725155165c8566650a406c789d to your computer and use it in GitHub Desktop.
Proxy pattern implemented in python-koans
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Proxy: | |
def __init__(self, target_object): | |
object.__setattr__(self, 'msg', OrderedDict()) | |
object.__setattr__(self, '_obj', target_object) | |
def __getattr__(self, name): | |
if name in self.msg: | |
self.msg[name] += 1 | |
else: | |
self.msg[name] = 1 | |
return getattr(self._obj, name) | |
def __setattr__(self, name, value): | |
if name in self.msg: | |
self.msg[name] += 1 | |
else: | |
self.msg[name] = 1 | |
setattr(self._obj, name, value) | |
class Television: | |
def power(self): | |
print("Power is on now") | |
# Usage | |
tv=Proxy(Television()) | |
tv.power() # Power is on now | |
print(tv.msg) # { 'power': 1 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment