
桥接模式是一种结构型设计模式, 主要用于将抽象部分与它的实现部分分离, 从而能在开发时分别使用,使系统更加灵活,易于扩展。

- #!/usr/bin/env python
- # -*- coding: UTF-8 -*-
- __doc__ = """
- 桥接模式
- 例:将不同形状和颜色相互独立,自由组合。无需创建组合类
- """
-
-
- class Shape:
- """形状基类"""
-
- def __init__(self, color):
- self._color = color
-
- def draw(self):
- pass
-
-
- class Color:
- """颜色基类"""
-
- def paint(self):
- pass
-
-
- class Square(Shape):
- """具体形状类"""
-
- def draw(self):
- return f"{self._color.paint()}的正方形"
-
-
- class Circle(Shape):
- """具体形状类"""
-
- def draw(self):
- return f"{self._color.paint()}的圆"
-
-
- class Triangle(Shape):
- """具体形状类"""
-
- def draw(self):
- return f"{self._color.paint()}的三角形"
-
-
- class Red(Color):
- """具体颜色类"""
-
- def paint(self):
- return "红色"
-
-
- class Blue(Color):
- """具体颜色类"""
-
- def paint(self):
- return "蓝色"
-
-
- # 客户端代码
- if __name__ == "__main__":
- """
- 红色的圆
- 红色的正方形
- 蓝色的圆
- 蓝色的正方形
- 红色的三角形
- 蓝色的三角形
- """
- print(Circle(Red()).draw())
- print(Square(Red()).draw())
-
- print(Circle(Blue()).draw())
- print(Square(Blue()).draw())
-
- # 若增加一个三角形,则只需要增加一个Triangle类
- print(Triangle(Red()).draw())
- print(Triangle(Blue()).draw())