结构型模式-桥接模式

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

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

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

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

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

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

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

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

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();
    }
相关推荐
BillKu1 小时前
推荐 Eclipse Temurin 的 OpenJDK
java·ide·eclipse
Morri31 小时前
[Java恶补day53] 45. 跳跃游戏Ⅱ
java·算法·leetcode
悟能不能悟1 小时前
eclipse怎么把项目设为web
java·eclipse
乂爻yiyao1 小时前
java 代理模式实现
java·开发语言·代理模式
2301_770373732 小时前
Java集合
java·开发语言
哈喽姥爷2 小时前
Spring Boot---自动配置原理和自定义Starter
java·spring boot·后端·自定义starter·自动配置原理
老华带你飞4 小时前
考研论坛平台|考研论坛小程序系统|基于java和微信小程序的考研论坛平台小程序设计与实现(源码+数据库+文档)
java·vue.js·spring boot·考研·小程序·毕设·考研论坛平台小程序
CHEN5_024 小时前
leetcode-hot100 11.盛水最多容器
java·算法·leetcode
songx_994 小时前
leetcode18(无重复字符的最长子串)
java·算法·leetcode
在路上`5 小时前
前端学习之后端java小白(三)-sql外键约束一对多
java·前端·学习