桥接模式(Bridge Pattern)

本文介绍了一种结构设计模式——桥接模式,通过分离抽象和实现类来提高代码的可扩展性和复用性。以绘制不同颜色圆圈为例,展示了如何使用桥接模式实现这一目的。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      从类的实现中分离出抽象或者接口类,以便于这两个类能够互不相干,这种模式称作桥接模式。这种类型模式属于结构设计模式之一, 它通过提供了一个桥结构来分离具体的实现类和抽象类。

      适用场合和优势:

  1.  想永久地分离抽象和实现类。
  2.  在多个对象中分享一个具体的实现类。
  3.  想去提高可扩展性。
  4.  从客户端哪里隐藏具体的实现。
     具体分析一个简单的实例,看看它是如何实现桥接模式。
     我们有一个接口DrawAPI, 桥接模式的实现类和它的之类RedCircleGreenCircle。Shape是一个抽象类,适用了DreawAPI类的实例对象。BridgePatternDemo作为测试类,测试有关内容。UML类如下:


      drawAPI接口类。
public interface DrawAPI {
    public void drawCircle(int radius, int x, int y);
}

     它的子类RedCircle、GreedCircle。
public class RedCircle implements DrawAPI {
    @Override
    public void drawCircle(int radius, int x, int y) {
        System.out.println("Drawing Circle[ color: red, radius: "
                              + radius +", x: " +x+", "+ y +"]");
    }
}

    
public class GreenCircle implements DrawAPI {
    @Override
    public void drawCircle(int radius, int x, int y) {
        System.out.println("Drawing Circle[ color: green, radius: "
                + radius +", x: " +x+", "+ y +"]");
    }
}
       
      定义一个抽象类Shape。
public abstract class Shape {
    protected DrawAPI drawAPI;
    protected Shape(DrawAPI drawAPI){
        this.drawAPI = drawAPI;
    }
    public abstract void draw();
}

     抽象类的子类.
public class Circle extends Shape {
    private int x, y, radius;

    public Circle(int x, int y, int radius, DrawAPI drawAPI) {
        super(drawAPI);
        this.x = x;
        this.y = y;
        this.radius = radius;
    }

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

     测试代码如下:
public class BridgePatternDemo {
    public static void main(String[] args) {
        Shape redCircle = new Circle(100,100, 10, new RedCircle());
        Shape greenCircle = new Circle(100,100, 10, new GreenCircle());

        redCircle.draw();
        greenCircle.draw();
    }
}

    测试结果:
Drawing Circle[ color: red, radius: 10, x: 100, 100]
Drawing Circle[ color: green, radius: 10, x: 100, 100]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值