Created
February 4, 2013 08:30
-
-
Save ZhanruiLiang/4705624 to your computer and use it in GitHub Desktop.
Decorator Pattern vs. Multiple Inheritance.
This file contains hidden or 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
| #!/usr/bin/python2 | |
| class Window(object): | |
| def draw(self, device): | |
| device.append('flat window') | |
| def info(self): | |
| pass | |
| # The subclass approch | |
| class BorderedWindow(Window): | |
| def draw(self, device): | |
| super(BorderedWindow, self).draw(device) | |
| device.append('borders') | |
| class ScrolledWindow(Window): | |
| def draw(self, device): | |
| super(ScrolledWindow, self).draw(device) | |
| device.append('scroll bars') | |
| # Here is the important point of this approch | |
| class MyWindow(ScrolledWindow, BorderedWindow, Window): | |
| pass | |
| def test_muli(): | |
| w = MyWindow() | |
| dev = [] | |
| w.draw(dev) | |
| print dev | |
| def test_muli2(): | |
| MyWindow = type('MyWindow', (ScrolledWindow, BorderedWindow, Window), {}) | |
| w = MyWindow() | |
| dev = [] | |
| w.draw(dev) | |
| print dev | |
| # The decorator approch | |
| class WindowDecorator: | |
| def __init__(self, w): | |
| self.window = w | |
| def draw(self, device): | |
| self.window.draw(device) | |
| def info(self): | |
| self.window.info() | |
| class BorderDecorator(WindowDecorator): | |
| def draw(self, device): | |
| self.window.draw(device) | |
| device.append('borders') | |
| class ScrollDecorator(WindowDecorator): | |
| def draw(self, device): | |
| self.window.draw(device) | |
| device.append('scroll bars') | |
| def test_deco(): | |
| # Here is the important point of this approch | |
| w = ScrollDecorator(BorderDecorator(Window())) | |
| dev = [] | |
| w.draw(dev) | |
| print dev | |
| test_muli() | |
| test_muli2() | |
| test_deco() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment