编程-设计模式 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();
    }
}
使用场景
  • 当你需要在抽象和实现之间建立一个松散耦合的关系时。
  • 当你需要独立地扩展抽象和实现的层次结构时。
  • 当一个类的实现细节不应该影响到使用它的客户时。

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

小结

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

相关推荐
Meya11279 小时前
U位资产管理系统:数据中心“最后一公里“的精细化治理
设计模式·开源·交互
Tockm11 小时前
vm网络配置桥接模式
网络·智能路由器·桥接模式
回忆2012初秋1 天前
工厂方法模式完整实现:GPS转换
设计模式·工厂方法模式
胡志辉的博客1 天前
多智能体协作,不是多开几个 Agent:从中介者模式看 OpenClaw 和 Hermes Agent
人工智能·设计模式·ai·agent·中介者模式·openclaw·herman
shark22222221 天前
能懂!基于Springboot的用户增删查改(三层设计模式)
spring boot·后端·设计模式
014-code1 天前
日志规范:怎么写才不算写废话
java·开发语言·设计模式·日志
楼田莉子1 天前
同步/异步日志系统:日志落地模块\日志器模块\异步日志模块
linux·服务器·c++·学习·设计模式
kyriewen111 天前
代码写成一锅粥?这5种设计模式让你的项目“起死回生”
前端·javascript·设计模式·typescript·ecmascript·html5
kyriewen1 天前
代码写成一锅粥?这5种设计模式让你的项目“起死回生”
前端·javascript·设计模式
两年半的个人练习生^_^1 天前
每日一学:设计模式之原型模式
java·开发语言·设计模式·原型模式