桥接模式
- 当你希望在多个对象之间共享实现时,使用桥接模式是一个好主意
- 桥接模式与适配器模式有相似之处,都是对不同对象之间的模式
- 适配器模式强调的是如何使不同对象协同工作,属于后期实现,桥接模式能够预先以解耦的方式定义抽象及其实现,属于预期实现。
实现
- 定义抽象接口,维护一个实现者(需要为帮助获取内容的实现类定义接口)的对象引用
- 为获取内容的实现类定义接口:python使用元类和抽象基类(ABC)定义等价的接口
- 实现实现者接口并定义其具体实现
- 主函数调用:
- 获取实现类对象
- 获取抽象接口对象,将实现类对象作为参数传递
- 调用抽象接口对象的维护方法
代码实现
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()