结构型模式-桥接模式

用于把抽象化与实现化解耦,使得二者可以独立变化。这种类型的设计模式属于结构型模式,它通过提供抽象化和实现化之间的桥接结构,来实现二者的解耦。

这种模式涉及到一个作为桥接的接口,使得实体类的功能独立于接口实现类,这两种类型的类可被结构化改变而互不影响。

桥接模式的目的是将抽象与实现分离,使它们可以独立地变化,该模式通过将一个对象的抽象部分与它的实现部分分离,使它们可以独立地改变。它通过组合的方式,而不是继承的方式,将抽象和实现的部分连接起来。

**意图:**将抽象部分与实现部分分离,使它们都可以独立的变化。

**主要解决:**在有多种可能会变化的情况下,用继承会造成类爆炸问题,扩展起来不灵活。

**何时使用:**实现系统可能有多个角度分类,每一种角度都可能变化。

**如何解决:**把这种多角度分类分离出来,让它们独立变化,减少它们之间耦合。

**关键代码:**抽象类依赖实现类。

java 复制代码
public interface DrawAPI {
     void drawCircle(int radius, int x, int y);
}
java 复制代码
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 +"]");
    }
}
java 复制代码
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 +"]");
    }
}
java 复制代码
public abstract class Shape {
    protected DrawAPI drawAPI;
    protected Shape(DrawAPI drawAPI){
        this.drawAPI = drawAPI;
    }
    public abstract void draw();
}
java 复制代码
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;
    }


    @Override
    public void draw() {
        drawAPI.drawCircle(radius,x,y);
    }
}
java 复制代码
    @Test
    public void test14(){
        Shape redCircle = new Circle(100,100, 10, new RedCircle());
        Shape greenCircle = new  Circle(100,100, 10, new GreenCircle());

        redCircle.draw();
        greenCircle.draw();
    }
相关推荐
兆子龙11 小时前
ahooks useRequest 深度解析:一个 Hook 搞定所有请求
java·javascript
兆子龙11 小时前
React Suspense 从入门到实战:让异步加载更优雅
java·javascript
刀法如飞13 小时前
AI时代,程序员都应该是算法思想工程师
人工智能·设计模式·程序员
咕白m62513 小时前
Java 实现 Excel 转 HTML:完整示例
java
RealPluto14 小时前
Spring AOP 失效排查
java·spring
码路飞14 小时前
热榜全是 OpenClaw,但我用 50 行 Python 就造了个桌面 AI Agent 🤖
java·javascript
Nyarlathotep011315 小时前
LinkedList源码分析
java·后端
用户83071968408215 小时前
Java 告别繁琐数据统计代码!MySQL 8 窗口函数真香
java·sql·mysql
带刺的坐椅15 小时前
SolonCode v0.0.20 发布 - 编程智能体(新增子代理和浏览器能力)
java·ai·agent·solon·solon-ai·claude-code·openclaw