场景
多个维度交叉组合,如
- 现有2种图案(圆和方),3种图形(红蓝绿),一共可以组成6种产品。
方案
将不同维度拆分开来, 通过组合获取结果,如图.这样不用为每一种可能罗列出实例类,同时各个维度的拓展性会更好。
uml
code
class Color(object):def __init__(self, color):self.color = colorclass Shape(object):def __init__(self, shape):self.shape = shapeclass FinalShape(object):def __init__(self, shape: Shape, color: Color):self._color = colorself._shape = shapedef show(self):return "{}的{}".format(self._color, self._shape)if __name__ == '__main__':color = Color('red')shape = Shape('circle')final_shape = FinalShape(shape, color)final_shape.show()
