编程-设计模式 7:桥接模式

设计模式 7:桥接模式

定义与目的
  • 定义 :桥接模式将抽象部分与它的实现部分分离,使得它们都可以独立地变化。
  • 目的 :该模式的主要目的是解耦一个类的抽象部分与其实现部分,使得这两部分可以独立地发展和变化。
实现示例

假设我们有一个图形库,需要支持不同平台上的图形绘制。我们可以使用桥接模式来实现这个需求。

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

// 定义实现部分 - 绘图接口
public interface DrawAPI {
    void draw();
}

// 具体实现 - 圆形
public class Circle implements Shape {
    private int x, y, radius;
    private DrawAPI drawAPI;

    public Circle(int x, int y, int radius, DrawAPI drawAPI) {
        this.x = x;
        this.y = y;
        this.radius = radius;
        this.drawAPI = drawAPI;
    }

    @Override
    public void draw() {
        drawAPI.draw();
        System.out.println("Drawing a circle with x: " + x + ", y: " + y + ", radius: " + radius);
    }
}

// 具体实现 - Windows 平台绘图
public class WindowsDrawAPI implements DrawAPI {
    @Override
    public void draw() {
        System.out.println("Drawing using Windows API");
    }
}

// 具体实现 - MacOS 平台绘图
public class MacOsDrawAPI implements DrawAPI {
    @Override
    public void draw() {
        System.out.println("Drawing using MacOS API");
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        DrawAPI windowsDrawAPI = new WindowsDrawAPI();
        DrawAPI macOsDrawAPI = new MacOsDrawAPI();

        Shape circleWindows = new Circle(100, 100, 10, windowsDrawAPI);
        Shape circleMacOs = new Circle(100, 100, 10, macOsDrawAPI);

        circleWindows.draw();
        circleMacOs.draw();
    }
}
使用场景
  • 当你需要在抽象和实现之间建立一个松散耦合的关系时。
  • 当你需要独立地扩展抽象和实现的层次结构时。
  • 当一个类的实现细节不应该影响到使用它的客户时。

桥接模式通过将抽象与实现分离,使得两者可以独立地变化和发展。这对于需要在不同的平台上提供相同功能的应用程序非常有用。

小结

桥接模式是一种常用的结构型模式,它可以帮助你解耦抽象与实现,使得两者可以独立地发展。这在需要支持多平台或多版本的系统中特别有用,因为它可以减少代码的重复,并提高系统的可维护性。

相关推荐
vx-bot5556667 小时前
企业微信接口在自动化工作流中的关键角色与设计模式
设计模式·自动化·企业微信
Yu_Lijing7 小时前
基于C++的《Head First设计模式》笔记——工厂模式
c++·笔记·设计模式
HL_风神21 小时前
设计原则之迪米特
c++·学习·设计模式
HL_风神21 小时前
设计原则之合成复用
c++·学习·设计模式
Aeside11 天前
揭秘 Nginx 百万并发基石:Reactor 架构与 Epoll 底层原理
后端·设计模式
帅气的你1 天前
从零封装一个通用的 API 接口返回类:统一前后端交互格式
java·设计模式
阿里巴巴淘系技术团队官网博客1 天前
GenAI输出内容控制的5种设计模式
设计模式
沛沛老爹1 天前
Skills高级设计模式(一):向导式工作流与模板生成
java·人工智能·设计模式·prompt·aigc·agent·web转型
__万波__1 天前
二十三种设计模式(二十二)--策略模式
java·设计模式·策略模式
Overt0p1 天前
抽奖系统(6)
java·spring boot·redis·设计模式·rabbitmq·状态模式