Java桥接案例

wen java案例 2

本文目录导读:

Java桥接案例

  1. 基础案例:图形绘制系统
  2. 进阶案例:消息发送系统
  3. 实际应用:多平台UI组件
  4. 桥接模式要点总结

我将为您提供一个完整的Java桥接模式(Bridge Pattern)案例,从基础到进阶,包含实际应用场景。

基础案例:图形绘制系统

问题场景

我们需要绘制不同类型的图形(圆形、矩形),每种图形可以使用不同的绘制方式(矢量绘制、光栅绘制)。

不使用桥接模式的方案(问题演示)

// 不使用桥接模式 - 会有类爆炸问题
abstract class Shape {
    abstract void draw();
}
// 四种组合类
class VectorCircle extends Shape {
    @Override
    void draw() {
        System.out.println("使用矢量绘制圆形");
    }
}
class RasterCircle extends Shape {
    @Override
    void draw() {
        System.out.println("使用光栅绘制圆形");
    }
}
class VectorRect extends Shape {
    @Override
    void draw() {
        System.out.println("使用矢量绘制矩形");
    }
}
class RasterRect extends Shape {
    @Override
    void draw() {
        System.out.println("使用光栅绘制矩形");
    }
}
// 如果增加新图形或新绘制方式,类会成倍增长!

使用桥接模式(解决方案)

// 1. 实现者接口(绘制方式)
interface DrawingAPI {
    void drawCircle(double x, double y, double radius);
    void drawRect(double x, double y, double width, double height);
}
// 2. 具体实现者A:矢量绘制
class VectorDrawing implements DrawingAPI {
    @Override
    public void drawCircle(double x, double y, double radius) {
        System.out.printf("矢量绘制圆形 - 圆心(%f,%f) 半径%f%n", x, y, radius);
    }
    @Override
    public void drawRect(double x, double y, double width, double height) {
        System.out.printf("矢量绘制矩形 - 位置(%f,%f) 尺寸%fx%f%n", x, y, width, height);
    }
}
// 3. 具体实现者B:光栅绘制
class RasterDrawing implements DrawingAPI {
    @Override
    public void drawCircle(double x, double y, double radius) {
        System.out.printf("光栅绘制圆形 - 圆心(%f,%f) 半径%f%n", x, y, radius);
    }
    @Override
    public void drawRect(double x, double y, double width, double height) {
        System.out.printf("光栅绘制矩形 - 位置(%f,%f) 尺寸%fx%f%n", x, y, width, height);
    }
}
// 4. 抽象类(图形)
abstract class Shape {
    protected DrawingAPI drawingAPI;
    protected Shape(DrawingAPI drawingAPI) {
        this.drawingAPI = drawingAPI;
    }
    abstract void draw();
    abstract void resizeByPercentage(double pct);
}
// 5. 扩展抽象类:圆形
class Circle extends Shape {
    private double x, y, radius;
    public Circle(double x, double y, double radius, DrawingAPI drawingAPI) {
        super(drawingAPI);
        this.x = x;
        this.y = y;
        this.radius = radius;
    }
    @Override
    void draw() {
        drawingAPI.drawCircle(x, y, radius);
    }
    @Override
    void resizeByPercentage(double pct) {
        radius *= (1 + pct / 100);
    }
}
// 6. 扩展抽象类:矩形
class Rectangle extends Shape {
    private double x, y, width, height;
    public Rectangle(double x, double y, double width, double height, DrawingAPI drawingAPI) {
        super(drawingAPI);
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
    @Override
    void draw() {
        drawingAPI.drawRect(x, y, width, height);
    }
    @Override
    void resizeByPercentage(double pct) {
        width *= (1 + pct / 100);
        height *= (1 + pct / 100);
    }
}
// 测试类
public class BridgePatternDemo {
    public static void main(String[] args) {
        // 创建不同的组合
        Shape circle1 = new Circle(10, 20, 5, new VectorDrawing());
        Shape circle2 = new Circle(15, 25, 8, new RasterDrawing());
        Shape rect1 = new Rectangle(30, 40, 10, 20, new VectorDrawing());
        Shape rect2 = new Rectangle(50, 60, 15, 25, new RasterDrawing());
        // 绘制所有图形
        System.out.println("=== 图形绘制演示 ===");
        circle1.draw();
        circle2.draw();
        rect1.draw();
        rect2.draw();
        // 调整大小后再绘制
        System.out.println("\n=== 调整大小后 ===");
        circle1.resizeByPercentage(50);  // 增大50%
        circle1.draw();
        rect2.resizeByPercentage(-20);   // 减小20%
        rect2.draw();
    }
}

进阶案例:消息发送系统

// 1. 实现者接口(消息发送渠道)
interface MessageSender {
    void send(String subject, String content);
}
// 2. 具体实现者A:邮件发送
class EmailSender implements MessageSender {
    @Override
    public void send(String subject, String content) {
        System.out.println("【邮件】主题:" + subject);
        System.out.println("      内容:" + content);
        System.out.println("      发送完成!");
    }
}
// 3. 具体实现者B:短信发送
class SmsSender implements MessageSender {
    @Override
    public void send(String subject, String content) {
        System.out.println("【短信】内容:" + subject + ":" + content);
        System.out.println("      发送完成!");
    }
}
// 4. 具体实现者C:微信发送
class WeChatSender implements MessageSender {
    @Override
    public void send(String subject, String content) {
        System.out.println("【微信】标题:" + subject);
        System.out.println("       正文:" + content);
        System.out.println("       发送完成!");
    }
}
// 5. 抽象类(消息类型)
abstract class Message {
    protected MessageSender sender;
    protected Message(MessageSender sender) {
        this.sender = sender;
    }
    abstract void sendMessage(String subject, String content);
}
// 6. 扩展抽象类:普通消息
class NormalMessage extends Message {
    public NormalMessage(MessageSender sender) {
        super(sender);
    }
    @Override
    void sendMessage(String subject, String content) {
        sender.send(subject, content);
    }
}
// 7. 扩展抽象类:加急消息
class UrgentMessage extends Message {
    private int urgencyLevel;
    public UrgentMessage(MessageSender sender, int urgencyLevel) {
        super(sender);
        this.urgencyLevel = urgencyLevel;
    }
    @Override
    void sendMessage(String subject, String content) {
        String urgentContent = "【加急级别" + urgencyLevel + "】" + content;
        String urgentSubject = "【紧急】" + subject;
        sender.send(urgentSubject, urgentContent);
        // 加急消息可以额外发送通知
        System.out.println("提示:已紧急通知相关人员!");
    }
}
// 8. 扩展抽象类:定时消息
class ScheduledMessage extends Message {
    private String scheduleTime;
    public ScheduledMessage(MessageSender sender, String scheduleTime) {
        super(sender);
        this.scheduleTime = scheduleTime;
    }
    @Override
    void sendMessage(String subject, String content) {
        System.out.println("计划" + scheduleTime + "发送消息:");
        sender.send("【定时】" + subject, content);
    }
}
// 测试
public class MessageBridgeDemo {
    public static void main(String[] args) {
        System.out.println("=== 消息发送系统演示 ===\n");
        // 创建发送渠道
        MessageSender email = new EmailSender();
        MessageSender sms = new SmsSender();
        MessageSender wechat = new WeChatSender();
        // 普通消息
        System.out.println("--- 普通邮件消息 ---");
        Message normalEmail = new NormalMessage(email);
        normalEmail.sendMessage("项目进度", "项目已按时完成第一阶段");
        System.out.println("\n--- 普通短信消息 ---");
        Message normalSms = new NormalMessage(sms);
        normalSms.sendMessage("验证码", "您的验证码是:123456");
        // 加急消息
        System.out.println("\n--- 加急微信消息 ---");
        Message urgentWeChat = new UrgentMessage(wechat, 3);
        urgentWeChat.sendMessage("服务器故障", "生产环境出现严重故障");
        // 定时消息
        System.out.println("\n--- 定时邮件消息 ---");
        Message scheduledEmail = new ScheduledMessage(email, "2024-01-15 10:00:00");
        scheduledEmail.sendMessage("周报", "这是本周工作汇报");
        // 动态组合能力展示
        System.out.println("\n--- 动态组合示例 ---");
        Message urgentEmail = new UrgentMessage(email, 1);
        urgentEmail.sendMessage("紧急会议", "请立即参加紧急会议");
    }
}

实际应用:多平台UI组件

// 1. 实现者接口(平台实现)
interface Platform {
    void render(String component, String style);
    void handleEvent(String event, String component);
}
// 2. 具体实现者:Windows平台
class WindowsPlatform implements Platform {
    @Override
    public void render(String component, String style) {
        System.out.println("Windows平台渲染" + component + ",样式:" + style);
    }
    @Override
    public void handleEvent(String event, String component) {
        System.out.println("Windows平台处理" + component + "的" + event + "事件");
    }
}
// 3. 具体实现者:Mac平台
class MacPlatform implements Platform {
    @Override
    public void render(String component, String style) {
        System.out.println("Mac平台渲染" + component + ",样式:" + style);
    }
    @Override
    public void handleEvent(String event, String component) {
        System.out.println("Mac平台处理" + component + "的" + event + "事件");
    }
}
// 4. 具体实现者:Linux平台
class LinuxPlatform implements Platform {
    @Override
    public void render(String component, String style) {
        System.out.println("Linux平台渲染" + component + ",样式:" + style);
    }
    @Override
    public void handleEvent(String event, String component) {
        System.out.println("Linux平台处理" + component + "的" + event + "事件");
    }
}
// 5. 抽象类(UI组件)
abstract class UIComponent {
    protected Platform platform;
    protected String style;
    protected UIComponent(Platform platform) {
        this.platform = platform;
        this.style = "默认样式";
    }
    abstract void display();
    abstract void handleInput(String event);
    protected void setStyle(String style) {
        this.style = style;
    }
}
// 6. 按钮组件
class Button extends UIComponent {
    private String label;
    public Button(Platform platform, String label) {
        super(platform);
        this.label = label;
    }
    @Override
    void display() {
        platform.render("按钮[" + label + "]", style);
    }
    @Override
    void handleInput(String event) {
        platform.handleEvent(event, "按钮[" + label + "]");
    }
}
// 7. 文本框组件
class TextBox extends UIComponent {
    private String placeholder;
    public TextBox(Platform platform, String placeholder) {
        super(platform);
        this.placeholder = placeholder;
    }
    @Override
    void display() {
        platform.render("文本框[占位符:" + placeholder + "]", style);
    }
    @Override
    void handleInput(String event) {
        platform.handleEvent(event, "文本框[占位符:" + placeholder + "]");
    }
}
// 8. 下拉列表组件
class DropDown extends UIComponent {
    private String[] options;
    public DropDown(Platform platform, String[] options) {
        super(platform);
        this.options = options;
    }
    @Override
    void display() {
        String optionStr = String.join(", ", options);
        platform.render("下拉列表[" + optionStr + "]", style);
    }
    @Override
    void handleInput(String event) {
        platform.handleEvent(event, "下拉列表");
    }
}
// 测试
public class UIComponentDemo {
    public static void main(String[] args) {
        System.out.println("=== 跨平台UI组件系统 ===\n");
        // 创建平台实例
        Platform windows = new WindowsPlatform();
        Platform mac = new MacPlatform();
        Platform linux = new LinuxPlatform();
        // Windows平台组件
        System.out.println("--- Windows平台组件 ---");
        Button winButton = new Button(windows, "登录");
        winButton.setStyle("现代风格");
        winButton.display();
        winButton.handleInput("点击");
        TextBox winTextBox = new TextBox(windows, "请输入用户名");
        winTextBox.display();
        winTextBox.handleInput("输入");
        // Mac平台组件
        System.out.println("\n--- Mac平台组件 ---");
        Button macButton = new Button(mac, "购买");
        macButton.setStyle("简洁风格");
        macButton.display();
        macButton.handleInput("悬停");
        DropDown macDropDown = new DropDown(mac, new String[]{"选项1", "选项2", "选项3"});
        macDropDown.display();
        macDropDown.handleInput("选择");
        // Linux平台组件
        System.out.println("\n--- Linux平台组件 ---");
        Button linuxButton = new Button(linux, "确认");
        linuxButton.setStyle("复古风格");
        linuxButton.display();
        linuxButton.handleInput("键盘输入");
        TextBox linuxTextBox = new TextBox(linux, "搜索...");
        linuxTextBox.display();
        // 动态切换平台(桥接模式的优势)
        System.out.println("\n--- 动态切换平台演示 ---");
        Button flexibleButton = new Button(windows, "灵活按钮");
        flexibleButton.display();
        // 运行时更换实现
        UIComponent[] components = {flexibleButton};
        // 模拟平台切换
        for (UIComponent component : components) {
            if (component instanceof Button) {
                // 实际应用中可以通过工厂模式创建新按钮
                Button newButton = new Button(mac, "灵活按钮");
                newButton.setStyle("时尚风格");
                newButton.display();
            }
        }
    }
}

桥接模式要点总结

优点

  1. 解耦抽象和实现:两者可以独立变化,互不影响
  2. 避免类爆炸:减少了类的数量
  3. 更好的扩展性:可以独立扩展抽象和实现

缺点

  1. 增加系统复杂度:增加了抽象层的理解难度
  2. 设计难度增加:需要正确的识别抽象和实现

适用场景

  • 需要跨越多个维度扩展系统时
  • 不希望使用继承导致类爆炸时
  • 需要在运行时切换实现时
  • 抽象和实现之间有稳定关系时

通过这些案例,可以看到桥接模式在解决多维度变化问题时的强大能力,使得系统更加灵活和可维护。

抱歉,评论功能暂时关闭!