桥梁模式

桥梁模式也属于结构性模式中的一种。
中间的接口在类与类之间充当“桥梁”的角色。
主要作用还是对代码之间进行抽象和解耦。
首先创建一个接口,作为及各类之间的“桥梁”。

public interface DrawAPI {
    public void draw(int radius,int x,int y);
}

这时候两根不同颜色的笔实现了DrawAPI接口,画出不同的颜色和形状。

RedPen

public class RedPen implements DrawAPI {
    @Override
    public void draw(int radius, int x, int y) {
        System.out.println("红笔 radius="+redius+" 从 x="+x+"  到y="+y);
    }
}

GreenPen

public class GreedPen implements DrawAPI {
    @Override
    public void draw(int radius, int x, int y) {
        System.out.println("绿笔 radius="+radius+" 从 x="+x+" 到 y="+y);
    }
}

这时候有个图形的抽象类BaseShape,需要画出不同的形状。因此构造方法中需要传入DrawAPI接口,并且两者之间是组合关系。

public abstract class BaseShape {
    protected DrawAPI drawAPI;
    protected BaseShape(DrawAPI drawAPI) {
        this.drawAPI = drawAPI;
    }
    public abstract void draw();
}

然后Circle和Rectangle继承BaseShape抽象类。

Rectangle

public class Rectangle extends BaseShape {
    private int radius,x,y;
    protected Rectangle(int radius, int x,int y,DrawAPI drawAPI) {
        super(drawAPI);
        this.radius = radius;
        this.x = x;
        this.y = y;
    }

    @Override
    public void draw() {
        drawAPI.draw(radius,x,y);
    }
}

Circle

public class Circle extends BaseShape {
    int radius;
    protected Circle(int radius,DrawAPI drawAPI) {
        super(drawAPI);
        this.radius = radius;
    }

    @Override
    public void draw() {
        drawAPI.draw(radius,0,0);
    }
}

来吧,测试一下这药怎么玩?

public class BridgeTest {
    public static void main(String[] args) {
    	// 画一个绿色的圆
        BaseShape greenCircle = new Circle(10, new GreedPen());
        // 画一个红色的矩形
        BaseShape redRectangle = new Rectangle(4, 8,9, new RedPen());
        greenCircle.draw();
        redRectangle.draw();
    }
}

在这里插入图片描述

这些类的依赖关系。

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值