Created
March 7, 2016 00:59
-
-
Save drhanlau/a97371a1b7b8102b793f to your computer and use it in GitHub Desktop.
Adapter Pattern
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
class Adapter: | |
def __init__(self, obj, adapted_methods): | |
self.obj = obj | |
self.__dict__.update(adapted_methods) | |
def __str__(self): | |
return str(self.obj) |
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
class Computer: | |
def __init__(self, name): | |
self.name = name | |
def __str__(self): | |
return 'the {} computer'.format(self.name) | |
def execute(self): | |
return 'executes a program' |
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
class Synthesizer: | |
def __init__(self, name): | |
self.name = name | |
def __str__(self): | |
return 'the {} synthesizer'.format(self.name) | |
def play(self): | |
return 'is playing an electronic song' |
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
def main(): | |
objects = [Computer('Asus')] | |
synth = Synthesizer('moog') | |
objects.append(Adapter(synth, dict(execute=synth.play))) | |
human = Human('Bob') | |
objects.append(Adapter(human, dict(execute=human.speak))) | |
for i in objects: | |
print('{} {}'.format(str(i), i.execute())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment