场景

多个维度交叉组合,如

  • 现有2种图案(圆和方),3种图形(红蓝绿),一共可以组成6种产品。

方案

将不同维度拆分开来, 通过组合获取结果,如图.这样不用为每一种可能罗列出实例类,同时各个维度的拓展性会更好。
image.png

uml
image.png
code

  1. class Color(object):
  2. def __init__(self, color):
  3. self.color = color
  4. class Shape(object):
  5. def __init__(self, shape):
  6. self.shape = shape
  7. class FinalShape(object):
  8. def __init__(self, shape: Shape, color: Color):
  9. self._color = color
  10. self._shape = shape
  11. def show(self):
  12. return "{}的{}".format(self._color, self._shape)
  13. if __name__ == '__main__':
  14. color = Color('red')
  15. shape = Shape('circle')
  16. final_shape = FinalShape(shape, color)
  17. final_shape.show()