Skip to content

Instantly share code, notes, and snippets.

@cjgiridhar
Created May 24, 2011 09:27
Show Gist options
  • Save cjgiridhar/988417 to your computer and use it in GitHub Desktop.
Save cjgiridhar/988417 to your computer and use it in GitHub Desktop.
Null Design Pattern
# 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