views:

455

answers:

1

I'm struggling with implementing the Bridge design pattern (or an alternative such as Adapter) in Python

I want to be able to write code like this to dump database schemas based on a supplied URL:

urls = ['sqlite://c:\\temp\\test.db', 'oracle://user:password@tns_name'];
for url in urls:
    db = Database(url);
    schema = db.schema()

I've got classes defined as

class Database():
    def __init__(self, url):
        self.db_type = string.split(self.url, "://")[0]

class Oracle():
    def schema(self):
        # Code to return Oracle schema

class SQLite():
    def schema(self):
        # Code to return SQLite schema

How can I "glue" these 3 classes together so I can get the first code block to execute correctly? I've Googled around, but must be having a thick day as it's just not coming together in my mind...

Thanks in advance

+10  A: 

Use a Factory pattern instead:

class Oracle(object):
  ...

class SQLite(object):
  ...

dbkind = dict(sqlite=SQLite, oracle=Oracle)

def Database(url):
  db_type, rest = string.split(self.url, "://", 1)
  return dbkind[db_type](rest)
Alex Martelli
Thanks Alex - works perfectly!
Dave
You're welcome Dave, but in that case why not Accept the answer?
Alex Martelli
Is there any advantage to using dict(sqlite=SQLite) over {'sqlite':SQLite}? Or is it just a matter of style?
HS
@statictype, strictly a matter of style: I'm very fond of the readable typenames (dict, list) over punctuation-based alternatives (another example: shallow copy a list with `list(thewidgets)` instead of doing it with `thewidgets[:]`). If you've ever had to discuss Perl code over the phone with a client you may better understand where I come from;-).
Alex Martelli