桥接模式简介

在Java中,桥接模式(Bridge Pattern)的核心思想是将抽象部分与其实现部分分离,使其可以独立变化。以下是桥接模式的一个简单示例,我们将创建一个图形渲染系统,该系统允许用户选择不同的形状(抽象部分)和不同的颜色策略(实现部分)。

首先,我们定义抽象部分------图形接口及其两个实现:

java 复制代码
// 抽象部分 - 图形接口
public interface Shape {
    void draw(ColorImplementor color);
}

// 抽象部分的实现 - 具体图形
public class Circle implements Shape {
    @Override
    public void draw(ColorImplementor color) {
        System.out.println("Drawing a circle with " + color.getColor());
    }
}

public class Rectangle implements Shape {
    @Override
    public void draw(ColorImplementor color) {
        System.out.println("Drawing a rectangle with " + color.getColor());
    }
}

// 实现部分的抽象接口 - 颜色策略
public interface ColorImplementor {
    String getColor();
}

// 实现部分的具体类 - 不同的颜色策略
public class RedColor implements ColorImplementor {
    @Override
    public String getColor() {
        return "Red";
    }
}

public class BlueColor implements ColorImplementor {
    @Override
    public String getColor() {
        return "Blue";
    }
}

然后,我们可以创建一个桥接使用的客户端代码:

java 复制代码
public class BridgePatternDemo {
    public static void main(String[] args) {
        Shape redCircle = new Circle();
        Shape blueRectangle = new Rectangle();

        ColorImplementor red = new RedColor();
        ColorImplementor blue = new BlueColor();

        // 组合图形与颜色策略
        redCircle.draw(red);
        blueRectangle.draw(blue);

        // 输出结果类似于:
        // Drawing a circle with Red
        // Drawing a rectangle with Blue
    }
}

在这个例子中,Shape是抽象部分,它定义了所有图形共有的行为(绘制),但是不关心如何绘制颜色。CircleRectangle是抽象部分的具体实现,它们都依赖于ColorImplementor接口来决定颜色策略。

ColorImplementor则是实现部分的抽象接口,RedColorBlueColor是它的具体实现。这样,我们就可以独立地修改图形种类或颜色策略,而不影响彼此的实现细节。这就是桥接模式的应用。

相关推荐
会员果汁4 天前
18.设计模式-桥接模式
设计模式·桥接模式
apolloyhl11 天前
Bridge 桥模式
桥接模式
北辰当尹14 天前
【实习之旅】Kali虚拟机桥接模式ping通百度
java·服务器·桥接模式
sxlishaobin14 天前
设计模式之桥接模式
java·设计模式·桥接模式
葡萄月令with蒲公英15 天前
NAT模式、路由模式、桥接模式 区别对比
智能路由器·桥接模式
a35354138216 天前
设计模式-桥接模式
c++·设计模式·桥接模式
蔺太微18 天前
桥接模式(Bridge Pattern)
设计模式·桥接模式
阿闽ooo25 天前
桥接模式实战:用万能遥控器控制多品牌电视
c++·设计模式·桥接模式
大白要努力!1 个月前
VMware 桥接模式完整配置手册
centos·桥接模式
sunriver20001 个月前
【VMware】Ubuntu在桥接模式下没有网络图标
ubuntu·桥接模式·vmware