设计模式-桥接模式

发布于:2025-07-02 ⋅ 阅读:(19) ⋅ 点赞:(0)

一、所需要的类

一个接口:抽象出行为
N个接口实现类:实现具体的行为
一个抽象类:里面封装上面的类作为元素,然后再进行自己的行为
N个抽象类实现类:进行行为
在这里插入图片描述

二、实现代码

行为接口

public interface Shape {
    public void draw();
}

行为接口是实现类1

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

行为接口是实现类2

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

上层抽象类

public abstract class Color {
    Shape shape;
    public abstract void applyColor();
}

抽象类实现类1

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

抽象类是实现类2

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

调用类

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

三、总结

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


网站公告

今日签到

点亮在社区的每一天
去签到