Created
May 24, 2011 09:27
-
-
Save cjgiridhar/988417 to your computer and use it in GitHub Desktop.
Null Design Pattern
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
# Null Object Pattern | |
class AbstractLogging: | |
def Log(self, msg): | |
pass | |
from time import asctime, localtime | |
class RealLogging(AbstractLogging): | |
def Log(self, msg): | |
print 'Logged at', asctime(localtime()), msg | |
class NullLogging(AbstractLogging): | |
def Log(self, msg): | |
return | |
# Proxy / wrapper around either null or real logger | |
class Logger: | |
def __init__(self): | |
self.On() | |
def Log(self, msg): | |
self.logger.Log(msg) | |
def On(self): | |
self.logger = RealLogging() | |
def Off(self): | |
self.logger = NullLogging() | |
Logger = Logger() | |
# Usage: | |
class API: | |
def doA(self): | |
Logger.Log('Am calling A') | |
print 'A done.' | |
def doB(self): | |
Logger.Log('Am calling B') | |
print 'B done.' | |
o = API() | |
o.doA() | |
o.doB() | |
Logger.Off() | |
o.doA() | |
o.doB() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment