将抽象化和实现化结构,使得二者可以独立变化
使用场景
一个类有两种独立变化的维度
Demo
"""桥接模式"""class DrawAPI:def draw_circle(self, *args, **kwargs):raise NotImplementedErrorclass RedCircle(DrawAPI):def draw_circle(self, radius, x, y):print(f"drawing circle red : {radius}, {x} ,{y}")class GreenCircle(DrawAPI):def draw_circle(self, radius, x, y):print(f"drawing circle green : {radius}, {x} ,{y}")class Shape:def __init__(self, draw_api: DrawAPI):self.draw_api = draw_apidef draw(self, radius, x, y):raise NotImplementedErrorclass Circle(Shape):def draw(self, radius, x, y):self.draw_api.draw_circle(radius, x, y)if __name__ == '__main__':red_circle = Circle(RedCircle())green_circle = Circle(GreenCircle())red_circle.draw(100, 10, 10)green_circle.draw(200, 20, 20)
