结构模式-桥接模式

1.桥接模式:

定义:将抽象与实现分离,使它们可以独立变化。它是用组合关系代替继承关系来实现,从而降低了抽象和实现这两个可变维度的耦合度。

优点:抽象与实现分离,扩展能力强;符合开闭原则;符合合成复用原则;其实现细节对客户透明

缺点:由于聚合关系建立在抽象层,要求开发者针对抽象化进行设计与编程,能正确地识别出系统中两个维度,这增加了系统的理解与设计难度。

不用桥接模式

如:业务中有2个维度(形状、颜色),每个维度有多个具体的实现

//抽象类
public interface ShapeAndColor{
     void draw();
}
//具体类 - 圆形红色
class CircleAndRed implements  ShapeAndColor{

    @Override
    public void draw() {
        System.out.println("红色圆");
    }
}
//具体类 - 矩形绿色
class RectangleAndGreen implements ShapeAndColor{

    @Override
    public void draw() {
        System.out.println("绿色矩形");
    }
}
//客户端调用
class Client{
     public static void main(String[] args) {
         //1
         ShapeAndColor circleAndRed=new CircleAndRed();
         circleAndRed.draw();
		//2
         ShapeAndColor rectangleAndGreen=new RectangleAndGreen();
         rectangleAndGreen.draw();
    }
}

从上面可以看出如果不用结构模式,当业务中有多个维度变化时,需要建立n*m个具体的类来满足业务
(n表示维度个数,m表每个维度的具体现实个数)

使用桥接模式

//抽象
public abstract class Shape {
    Color color;
    public void setColor(Color color) {
        this.color = color;
    }

    public abstract void draw();
}
class Circle extends Shape{

    public void draw() {
        color.bepaint("圆");
    }
}

class Rectangle extends Shape{
    public void draw() {
        color.bepaint("长方形");
    }
}

//具体
public interface Color {
    public void bepaint(String shape);
}
class White implements Color{
    public void bepaint(String shape) {
        System.out.println("白色的" + shape);
    }
}
class Gray implements Color{
    public void bepaint(String shape) {
        System.out.println("灰色的" + shape);
    }
}
//客户端
public class Client {
    public static void main(String[] args) {
        //白色
        Color white = new White();
        //长方形
        Shape rectange = new Rectangle();
        rectange.setColor(white);
        rectange.draw();

        //圆形
        Shape circle = new Circle();
        circle.setColor(white);
        circle.draw();
    }
}

使用了桥接模式,使颜色(具体)和形状(抽象)两个维度分类开了,客户端可以自由的组合这个两个维度。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值