设计模式-桥接模式

一、所需要的类

一个接口:抽象出行为

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();
    }
}

三、总结

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

相关推荐
青衫码上行5 分钟前
【从0开始学习Java | 第17篇】集合(中-Set部分)
java·学习
武子康10 分钟前
Java-122 深入浅出 MySQL CAP理论详解与分布式事务实践:从2PC到3PC与XA模式
java·大数据·数据库·分布式·mysql·性能优化·系统架构
田青钊17 分钟前
Zookeeper核心知识全解:节点类型、集群架构与选举机制
java·分布式·zookeeper
码畜也有梦想18 分钟前
springboot响应式编程笔记
java·spring boot·笔记
LoveXming20 分钟前
Chapter4—工厂方法模式
c++·设计模式·简单工厂模式·工厂方法模式·开闭原则
王同学 学出来33 分钟前
跟做springboot尚品甄选项目(二)
java·spring boot·后端
zcz160712782141 分钟前
LVS + Keepalived 高可用负载均衡集群
java·开发语言·算法
@CLoudbays_Martin111 小时前
CDN是否能有效检测并且同时防御Ddos 和 CC 攻击?
java·服务器·网络·数据库·git·数据库开发·时序数据库
知彼解己2 小时前
字符串大数相加:从初稿到优化的思路演进
java·开发语言·算法
拾忆,想起2 小时前
Redisson 分布式锁的实现原理
java·开发语言·分布式·后端·性能优化·wpf