python桥接模式学习

桥接模式

  • 当你希望在多个对象之间共享实现时,使用桥接模式是一个好主意
  • 桥接模式与适配器模式有相似之处,都是对不同对象之间的模式
  • 适配器模式强调的是如何使不同对象协同工作,属于后期实现,桥接模式能够预先以解耦的方式定义抽象及其实现,属于预期实现。

实现

  1. 定义抽象接口,维护一个实现者(需要为帮助获取内容的实现类定义接口)的对象引用
  2. 为获取内容的实现类定义接口:python使用元类和抽象基类(ABC)定义等价的接口
  3. 实现实现者接口并定义其具体实现
  4. 主函数调用:
    • 获取实现类对象
    • 获取抽象接口对象,将实现类对象作为参数传递
    • 调用抽象接口对象的维护方法

代码实现

import abc
import urllib.parse
import urllib.request


class ResourceContent:
    """
    Define the abstraction's interface.
    Maintain a reference to an object which represents the Implementor.
    """

    def __init__(self, imp):
        self._imp = imp

    def show_content(self, path):
        self._imp.fetch(path)


class ResourceContentFetcher(metaclass=abc.ABCMeta):
    """
    Define the interface (Implementor) for implementation classes that help fetch content.
    """
    
    @abc.abstractmethod
    def fetch(path):
        pass
        

class URLFetcher(ResourceContentFetcher):
    """
    Implement the Implementor interface and define its concrete
    implementation.
    """
    
    def fetch(self, path):
        # path is an URL
        req = urllib.request.Request(path)
        with urllib.request.urlopen(req) as response:
            if response.code == 200:
                the_page = response.read()
                print(the_page)
                        
                
class LocalFileFetcher(ResourceContentFetcher):
    """
    Implement the Implementor interface and define its concrete
    implementation.
    """

    def fetch(self, path):
        # path is the filepath to a text file
        with open(path) as f:
            print(f.read())
        
       
def main():
    url_fetcher = URLFetcher()
    iface = ResourceContent(url_fetcher)
    iface.show_content('http://python.org')

    print('===================')
    
    localfs_fetcher = LocalFileFetcher()
    iface = ResourceContent(localfs_fetcher)
    iface.show_content('file.txt')

    
if __name__ == "__main__":
    main()

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一切如来心秘密

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值