Python design patterns #2: adapter, bridge and proxy

· Design Patterns, Python

Finally got the time to complete this project, since I first started it with the classic Singleton. Later I’ll post about the Borg pattern, which is the pythonic version of how singleton should have been..


Adapter, Bridge and Proxy are all about can’t / won’t / prefer-not-to do something directly, but by other mean. They’re all quite the simple ones and the recipes are self explanatory:


Adapter: adapt interface1 to inteface2

Really meant for: adapting your current interface to an old / legacy / 3rd party one.

class Target:

 def meth1(p1, p2):
 print (p1 + ", " + p2)

class Adapter:

 def meth2(p1, p2, p3):
 Target.meth1(p1, p2 + " and " + p3)

if __name__ == '__main__':
 Adapter.meth2('here', 'there', 'everywhere')

>>> here, there and everywhere

Bridge: bridging abstraction and implementation layers

Really meant for: separation of layers, both maintained by you, in a planned in advance scenario

class Implementation(object):

    def interface1(self, p1, p2):
        print (p1 + ", " + p2)

class Bridge(object):

    def __init__(self):
        self.impl = Implementation()

    def interface2(self, p1, p2, p3):
        self.impl.interface1(p1, p2 + " and " + p3)

if __name__ == '__main__':
    Bridge().interface2('here', 'there', 'everywhere')

>>> here, there and everywhere


Proxy: are you talking to me?

Really meant for: safer, expensive or impossible to do so directly, needs some handling before moving on, etc..

Unlike Adapter and Bridge, Proxy has the exact interface of the Target class, allowing it to really do everything on its behalf

from time import sleep
from string import upper

class Base(object):

 def interface1(self, p1):
 raise NotImplementedError('this class acts as an Interface')

class Target(Base):

 def interface1(self, p1):
 print('target got on interface1: ' + p1)

class Proxy(Base):

 def interface1(self, p1):
 print('proxy got on interface1: ' + p1 + '. consider it done.')
 print('proxy does something, like sleeping and CAPSing')

if __name__ == '__main__':
 Proxy().interface1('this and that')

>>> proxy got on interface1: this and that. consider it done.
>>> proxy does something, like sleeping and CAPSing
>>> target got on interface1: THIS AND THAT


1 Comment

Comments RSS

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: