Skip to content

Instantly share code, notes, and snippets.

@lele85
Created January 31, 2012 20:36
Show Gist options
  • Save lele85/1712750 to your computer and use it in GitHub Desktop.
Save lele85/1712750 to your computer and use it in GitHub Desktop.
Dependency Injection Hello World in python
from datetime import *
class ConsoleMessageWriter:
def __init__(self):
pass
def write(self, message):
print message
class LoggedMessageWriter:
def __init__(self, writer):
if writer == None:
raise Exception("writer is null")
self.writer = writer
def write(self,message):
self.__log(message);
self.writer.write(message);
def __log(self, message):
now = datetime.now()
print "[INFO] - {:%Y-%m-%d %H:%M:%S} - Writing attempt".format(now)
class PasswordProtectedMessageWriter:
def __init__(self, writer, password):
self.__password = password;
if writer == None:
raise Exception("writer is null")
self.writer = writer
def write(self, message):
self.__askPassword()
self.writer.write(message)
def __askPassword(self):
guessPassword = raw_input("Ultra secure message writer... insert secret password: ")
if self.__password != guessPassword:
raise Exception("Wrong password!")
pass
class MultiChannelWriter:
def __init__(self, writers):
self.writers = writers
def write(self, message):
for writer in self.writers:
print "\n***"+writer.__class__.__name__+"***"
try:
writer.write(message)
except Exception, e:
print e.message
else:
pass
finally:
pass
def main():
writer = ConsoleMessageWriter()
loggedWriter = LoggedMessageWriter(writer)
passwordLoggedWriter = PasswordProtectedMessageWriter(loggedWriter, "secret")
anotherWriter = ConsoleMessageWriter()
anotherLoggedWriter = LoggedMessageWriter(writer)
simpleMessageWriter = ConsoleMessageWriter()
multichannelWriter = MultiChannelWriter([passwordLoggedWriter, anotherLoggedWriter, simpleMessageWriter])
multichannelWriter.write("Messaggio")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment