【问题标题】:Python - how to implement Bridge (or Adapter) design pattern?Python - 如何实现桥(或适配器)设计模式?
【发布时间】:2009-05-25 04:12:43
【问题描述】:

我正在努力在 Python 中实现 Bridge 设计模式(或适配器等替代方案)

我希望能够编写这样的代码来根据提供的 URL 转储数据库模式:

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

我的类定义为

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

如何将这 3 个类“粘合”在一起,以便正确执行第一个代码块?我在 Google 上四处搜索,但一定是度过了充实的一天,因为我并没有想到它......

提前致谢

【问题讨论】:

    标签: python design-patterns


    【解决方案1】:

    改用工厂模式:

    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)
    

    【讨论】:

    • 不客气,戴夫,但既然如此,为什么不接受答案呢?
    • 在 {'sqlite':SQLite} 上使用 dict(sqlite=SQLite) 有什么好处吗?还是只是风格问题?
    • @statictype,严格来说是风格问题:我非常喜欢可读的类型名(dict,list)而不是基于标点符号的替代品(另一个例子:用list(thewidgets)而不是浅拷贝一个列表使用thewidgets[:])。如果您曾经不得不通过电话与客户讨论 Perl 代码,您可能会更好地理解我来自哪里;-)。
    猜你喜欢
    • 2012-05-25
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    相关资源
    最近更新 更多