Python设计模式——桥接模式(Bridge)
桥接模式(Bridge)
目标:将抽象化(Abstraction)与实现化(Implementation)解耦,使得二者可以独立地变化。
优点:类和示例分离,二者可以独立设计,不受约束
缺点:系统可读性降低
结构
- 抽象化(Abstraction): 抽象化角色给出定义,并保存一个对实现化角色的引用。
- 实现化(Implementation):给出实现化角色的接口,但并不包含具体的实现。需要注意的是,这里的接口可以是一个封装。
- 修正抽象化(Refined Abstraction): 对抽象化角色进行改变。
- 具体实现化(Concrete Implementor): 实现化角色接口的具体实现
示例1-圆
# 这个示例仅包含了修正抽化画角色和具体实现化角色
# ConcreteImplementor 1/2
class DrawingAPI1:
def draw_circle(self, x, y, radius):
print(f"API1.circle at {x}:{y} radius {radius}")
# ConcreteImplementor 2/2
class DrawingAPI2:
def draw_circle(self, x, y, radius):
print(f"API2.circle at {x}:{y} radius {radius}")
# Refined Abstraction
class CircleShape:
def __init__(self, x, y, radius, drawing_api):
self._x = x
self._y = y
self._radius = radius
self._drawing_api = drawing_api
# low-level i.e. Implementation specific
def draw(self):
self._drawing_api.draw_circle(self._x, self._y, self._radius)
# high-level i.e. Abstraction specific
def scale(self, pct):
self._radius *= pct
if __name__ == '__main__':
shape0 = CircleShape(1, 2, 3, DrawingAPI1())
shape1 = CircleShape(5, 7, 7, DrawingAPI2())
CircleShape(5, 7, 11, DrawingAPI2())
for shape in (shape0, shape1):
shape.scale(2.5)
shape.draw()
# 预期输出:
# API1.circle at 1:2 radius 7.5
# API2.circle at 5:7 radius 27.5
示例2-手机
import abc
# 抽象
class Mobile(metaclass=abc.ABCMeta):
def __init__(self, cover):
self.cover = cover
@abc.abstractmethod
def buy(self):
pass
# 实现者
class Cover(metaclass=abc.ABCMeta):
@abc.abstractmethod
def put(self):
pass
# 细化抽象
class Xiaomi(Mobile):
def buy(self):
self.cover.put(self)
# 细化抽象
class Huawei(Mobile):
def buy(self):
self.cover.put(self)
# 细化抽象
class Iphone(Mobile):
def buy(self):
self.cover.put(self)
# 具体实现者
class YellowCover(Cover):
def put(self, mobile):
print(f"套着{self.__class__.__name__}的{mobile.__class__.__name__}")
# 具体实现者
class RedCover(Cover):
def put(self, mobile):
print(f"套着{self.__class__.__name__}的{mobile.__class__.__name__}")
# 具体实现者
class GreenCover(Cover):
def put(self, mobile):
print(f"套着{self.__class__.__name__}的{mobile.__class__.__name__}")
if __name__ == "__main__":
red_xiaomi = Xiaomi(RedCover())
red_xiaomi.buy()
green_huawei = Huawei(GreenCover())
green_huawei.buy()
red_huawei = Huawei(RedCover())
red_huawei.buy()
yellow_iphone = Iphone(YellowCover())
yellow_iphone.buy()
ref
https://blog.csdn.net/qq_40329976/article/details/103963290
本文来自博客园,作者:坦先生的AI资料室,转载请注明原文链接:https://www.cnblogs.com/yushengchn/p/16521915.html