设计模式-桥接模式

一、所需要的类

一个接口:抽象出行为

N个接口实现类:实现具体的行为

一个抽象类:里面封装上面的类作为元素,然后再进行自己的行为

N个抽象类实现类:进行行为

二、实现代码

行为接口

java 复制代码
public interface Shape {
    public void draw();
}

行为接口是实现类1

java 复制代码
public class Square implements Shape {
    @Override
    public void draw() {
        System.out.println("画了一个正方形");
    }
}

行为接口是实现类2

java 复制代码
public class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("画了一个圆");
    }
}

上层抽象类

java 复制代码
public abstract class Color {
    Shape shape;
    public abstract void applyColor();
}

抽象类实现类1

java 复制代码
public class BlueColor extends Color{
    public BlueColor(Shape shape)
    {
        this.shape = shape;
    }
    @Override
    public void applyColor() {
        shape.draw();
        System.out.println("喷上蓝色");
    }
}

抽象类是实现类2

java 复制代码
public class RedColor extends Color{
    public RedColor(Shape shape) {
        this.shape = shape;
    }
    @Override
    public void applyColor() {
        shape.draw();
        System.out.println("喷上红色");
    }
}

调用类

java 复制代码
@SpringBootApplication
public class BridgeApplication {
    public static void main(String[] args) {
        Square square = new Square();
        BlueColor blueColor = new BlueColor(square);
        RedColor redColor = new RedColor(square);
        blueColor.applyColor();
        redColor.applyColor();
        Square square1 = new Square();
        BlueColor blueColor1 = new BlueColor(square1);
        RedColor redColor1 = new RedColor(square1);
        blueColor1.applyColor();
        redColor1.applyColor();
    }
}

三、总结

桥接模式,处理的是多对多的组合,一层套一层

相关推荐
karry_k8 小时前
MyBatis批量insert-select踩坑:useGeneratedKeys=true 可能让PostgreSQL返回大量插入结果
java·后端
karry_k8 小时前
PostgreSQL 在 MyBatis 中执行正常 SQL 失效:一次 DELETE USING 踩坑记录
java·后端
SamDeepThinking12 小时前
从源码到代码:MyBatis-Flex 与 MyBatis-Plus 的逐项对比
java·后端·程序员
她的男孩15 小时前
Spring Boot 接 Flowable 工作流:用 3 个注解搭一个请假审批流程
java·后端·架构
荣码16 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
plainGeekDev18 小时前
Gson → kotlinx.serialization
android·java·kotlin
小bo波1 天前
Java Swing 图形用户界面实验 —— 从算术练习到游戏开发的完整实践
java·课程设计·gui·游戏开发·扫雷·swing
咖啡八杯1 天前
GoF设计模式——备忘录模式
java·后端·spring·设计模式