Skip to content

Instantly share code, notes, and snippets.

Created August 15, 2011 07:38
  • Star 31 You must be signed in to star a gist
  • Fork 15 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Example of `adapter' design pattern in Python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Example of `adapter' design pattern
# Copyright (C) 2011 Radek Pazdera
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <>.
# Adaptee (source) interface
class EuropeanSocketInterface:
def voltage(self): pass
def live(self): pass
def neutral(self): pass
def earth(self): pass
# Adaptee
class Socket(EuropeanSocketInterface):
def voltage(self):
return 230
def live(self):
return 1
def neutral(self):
return -1
def earth(self):
return 0
# Target interface
class USASocketInterface:
def voltage(self): pass
def live(self): pass
def neutral(self): pass
# The Adapter
class Adapter(USASocketInterface):
__socket = None
def __init__(self, socket):
self.__socket = socket
def voltage(self):
return 110
def live(self):
def neutral(self):
return self.__socket.neutral()
# Client
class ElectricKettle:
__power = None
def __init__(self, power):
self.__power = power
def boil(self):
if self.__power.voltage() > 110:
print "Kettle on fire!"
if == 1 and \
self.__power.neutral() == -1:
print "Coffee time!"
print "No power."
def main():
# Plug in
socket = Socket()
adapter = Adapter(socket)
kettle = ElectricKettle(adapter)
# Make coffee
return 0
if __name__ == "__main__":
Copy link

jpic commented Mar 9, 2018

Great example ! Did you think of making an adapter interface for common python developer problems with recursive adapter mapping ? It would be really nice if you could share it otherwise Im reinventing in mjtamlyn/django-adapters#40

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment