结构——桥接模式

桥接模式是将抽象和实现分离开,或者说用组合去替代继承。

比如画图形,话白色的圆,白色的矩形,红色的圆形,红色的矩形,白色三角形,红色三角形

如果使用继承,则定义Shape类

WhiteCircle,WhiteRect,RedCircle,RedRect,WhiteTri,RedTri四个类

如果再继续添加颜色或者添加图形类型,如蓝色,那么需要添加三个类最终也就是九个

桥接模式就是将颜色和图形两个维度区分开分别实现,在组合到一起,这样最终只需要六个类,White,Blue,Red,Circle,Rectangle,Triangle

定义Shape

Shape{
  color;
  draw(){
    color.execute();
    figure.execute();
  }
}

定义圆形CircleShape

CircleShape implements Shape{
  CircleShpae(Color color){
  }
  draw(){
    color.draw();
    syso("画圆");
  }
}

其实不太懂为什么不让形状和颜色都作为shape的成员属性算了

猜你喜欢

转载自blog.csdn.net/a397525088/article/details/82918589