Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - how to implement Bridge (or Adapter) design pattern?

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

like image 484
Dave Avatar asked May 25 '09 04:05

Dave


People also ask

What is a bridge in Python?

Bridge is a structural design pattern that divides business logic or huge class into separate class hierarchies that can be developed independently. One of these hierarchies (often called the Abstraction) will get a reference to an object of the second hierarchy (Implementation).

What is Adapter pattern in Python?

Adapter is a structural design pattern, which allows incompatible objects to collaborate. The Adapter acts as a wrapper between two objects. It catches calls for one object and transforms them to format and interface recognizable by the second object.

Is Python good for design patterns?

Yes, Python has design patterns. In fact, design patterns are simply ways to solve problems; they are independent of any programming language. You can implement most design patterns in a wide range of programming languages.


1 Answers

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)
like image 191
Alex Martelli Avatar answered Oct 07 '22 22:10

Alex Martelli