Created
July 8, 2015 06:28
-
-
Save calderonroberto/6a059c96742b6edbb6cf to your computer and use it in GitHub Desktop.
Chain of responsibility in python (Design Patterns - Gamma, Helm, Johnson, Vlissides)
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
PRINT_TOPIC = 1 | |
PAPER_ORIENTATION = 2 | |
APPLICATION_TOPIC = 3 | |
NO_HELP_TOPIC = -1 | |
class HelpHandler (object): | |
def __init__(self, successor=0, topic=NO_HELP_TOPIC): | |
self._successor = successor | |
self._topic = topic | |
def HasHelp(self): | |
return self._topic != NO_HELP_TOPIC; | |
def HandleHelp(self): | |
if self._successor != 0: | |
self._successor.HandleHelp() | |
def SetHandler(self,h,t): | |
self._successor = h | |
self._h = t | |
class Widget(HelpHandler): | |
def __init__(self, w, t): | |
super(Widget,self).__init__(w,t) | |
class Button(Widget): | |
def __init__(self, d, t): | |
super(Button,self).__init__(d,t) | |
def HandleHelp(self): | |
if self.HasHelp(): | |
print "Button Help" | |
else: | |
return super(Button, self).HandleHelp() | |
class Dialog(Widget): | |
def __init__(self, h, t): | |
super(Dialog,self).__init__(h,t) | |
self.SetHandler(h,t) | |
def HandleHelp(self): | |
if self.HasHelp(): | |
print "Dialog Help" | |
else: | |
return super(Dialog, self).HandleHelp() | |
class Application(HelpHandler): | |
def __init__(self, t): | |
super(Application,self).__init__(0,t) | |
def HandleHelp(self): | |
print "Application Help" | |
def main(): | |
application = Application(APPLICATION_TOPIC) | |
dialog = Dialog(application, PRINT_TOPIC) | |
button = Button(dialog, NO_HELP_TOPIC) | |
# invoking help in the chain | |
button.HandleHelp() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment