Skip to content

Instantly share code, notes, and snippets.

@ferdef
Last active January 29, 2018 09:27
Show Gist options
  • Save ferdef/62bb1295cd5b1759128a7f916e60d984 to your computer and use it in GitHub Desktop.
Save ferdef/62bb1295cd5b1759128a7f916e60d984 to your computer and use it in GitHub Desktop.
Adapter pattern
class Dog(object):
'''A representation of a dog'''
def __init__(self, name):
self.name = name
def bark(self):
return 'Woof!!'
class Person:
'''A representation of a person'''
def __init__(self, name):
self.name = name
def make_noise(self):
return 'Hello!!'
class DogAdapter:
'''Adapts the Dog class through encapsulation'''
def __init__(self, canine):
self.canine = canine
def make_noise(self):
'''This is the only method that's adapted'''
return self.canine.bark()
def __getattr__(self, attr):
'''Everything else is delegated to the object'''
return getattr(self.canine, attr)
def interact_with_creature(creature):
'''
React to an event by showing the creature's name and what it says
'''
return (creature.name, creature.make_noise())
person = Person('John')
dog = Dog('Sprocket')
dog_adapter = DogAdapter(dog)
print(interact_with_creature(person))
print(interact_with_creature(dog_adapter))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment