|
|
|
|
'''
|
|
|
|
|
桥接模式(Bridge Pattern)可以将抽象与实现解耦,让它们可以独立变化。
|
|
|
|
|
这在处理多种分类的书籍时特别有用,比如你想在不同的平台上展示这些书籍,同时这些书籍还分属不同的分类。
|
|
|
|
|
下面是一个简单的实现代码示例,展示如何使用桥接模式来构建书城的书籍分类与展示平台:
|
|
|
|
|
'''
|
|
|
|
|
|
|
|
|
|
# 定义书籍接口
|
|
|
|
|
class IBook:
|
|
|
|
|
def get_title(self):
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
def get_author(self):
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
# 具体书籍实现
|
|
|
|
|
class NovelBook(IBook):
|
|
|
|
|
def __init__(self, title, author):
|
|
|
|
|
self.title = title
|
|
|
|
|
self.author = author
|
|
|
|
|
|
|
|
|
|
def get_title(self):
|
|
|
|
|
return self.title
|
|
|
|
|
|
|
|
|
|
def get_author(self):
|
|
|
|
|
return self.author
|
|
|
|
|
|
|
|
|
|
# 定义抽象分类
|
|
|
|
|
class BookCategory:
|
|
|
|
|
def __init__(self, name):
|
|
|
|
|
self.name = name
|
|
|
|
|
self.books = []
|
|
|
|
|
|
|
|
|
|
def add_book(self, book):
|
|
|
|
|
self.books.append(book)
|
|
|
|
|
|
|
|
|
|
def get_books(self):
|
|
|
|
|
return self.books
|
|
|
|
|
|
|
|
|
|
# 定义抽象展示平台
|
|
|
|
|
class DisplayPlatform:
|
|
|
|
|
def display(self, book):
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
# 具体展示平台实现
|
|
|
|
|
class WebDisplayPlatform(DisplayPlatform):
|
|
|
|
|
def display(self, book):
|
|
|
|
|
return f"On the web: {book.get_title()} by {book.get_author()}"
|
|
|
|
|
|
|
|
|
|
class MobileDisplayPlatform(DisplayPlatform):
|
|
|
|
|
def display(self, book):
|
|
|
|
|
return f"On mobile: {book.get_title()} by {book.get_author()}"
|
|
|
|
|
|
|
|
|
|
# 桥接类,将分类与展示平台连接起来
|
|
|
|
|
class BookShop:
|
|
|
|
|
def __init__(self, category, platform):
|
|
|
|
|
self.category = category
|
|
|
|
|
self.platform = platform
|
|
|
|
|
|
|
|
|
|
def show_books(self):
|
|
|
|
|
for book in self.category.get_books():
|
|
|
|
|
print(self.platform.display(book))
|
|
|
|
|
|
|
|
|
|
# 客户端代码
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
# 创建书籍
|
|
|
|
|
novel1 = NovelBook("The Great Gatsby", "F. Scott Fitzgerald")
|
|
|
|
|
novel2 = NovelBook("1984", "George Orwell")
|
|
|
|
|
|
|
|
|
|
# 创建分类
|
|
|
|
|
fiction_category = BookCategory("Fiction")
|
|
|
|
|
fiction_category.add_book(novel1)
|
|
|
|
|
fiction_category.add_book(novel2)
|
|
|
|
|
|
|
|
|
|
# 创建展示平台
|
|
|
|
|
web_platform = WebDisplayPlatform()
|
|
|
|
|
mobile_platform = MobileDisplayPlatform()
|
|
|
|
|
|
|
|
|
|
# 创建书城并展示书籍
|
|
|
|
|
web_bookshop = BookShop(fiction_category, web_platform)
|
|
|
|
|
web_bookshop.show_books()
|
|
|
|
|
|
|
|
|
|
mobile_bookshop = BookShop(fiction_category, mobile_platform)
|
|
|
|
|
mobile_bookshop.show_books()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
'''
|
|
|
|
|
在这个示例中,IBook 是一个接口,定义了书籍应有的行为(比如获取标题和作者)。NovelBook 是一个具体书籍类,实现了 IBook 接口。BookCategory 是一个书籍分类类,它可以包含多个书籍实例。
|
|
|
|
|
|
|
|
|
|
DisplayPlatform 是一个抽象展示平台类,定义了如何展示书籍。WebDisplayPlatform 和 MobileDisplayPlatform 是具体展示平台类,分别实现了 DisplayPlatform 接口,以提供不同的展示方式。
|
|
|
|
|
|
|
|
|
|
BookShop 是一个桥接类,它将书籍分类与展示平台连接起来,通过 show_books 方法可以展示分类中的所有书籍。
|
|
|
|
|
'''
|