Java Bridge模式

引言

Bridge模式是一种结构型设计模式,它可以将抽象和实现解耦,使它们可以独立地变化。这种模式有助于解决多维度变化的问题,同时提供了更灵活、可扩展的设计。本文将介绍Bridge模式的概念、使用场景、实现方式,并通过Java代码示例来加深理解。

概念

Bridge模式将抽象和实现分离,使它们可以独立地变化,从而实现抽象和实现的解耦。它使用组合关系而不是继承关系,将抽象和实现的变化分别封装在两个类中,通过将抽象类作为桥梁,将不同的实现类连接起来。

结构

Bridge模式包含以下角色:

  • Abstraction(抽象类):定义抽象类的接口,包含对实现类的引用。
  • RefinedAbstraction(修正抽象类):扩展抽象类的接口,提供更具体的实现。
  • Implementor(实现类接口):定义实现类的接口。
  • ConcreteImplementor(具体实现类):实现Implementor接口的具体类。

下面用类图表示Bridge模式的结构:

classDiagram
    class Abstraction {
        +Implementor implementor
        +operation()
    }
    class RefinedAbstraction {
        +operation()
    }
    interface Implementor {
        +operationImpl()
    }
    class ConcreteImplementorA {
        +operationImpl()
    }
    class ConcreteImplementorB {
        +operationImpl()
    }
    Abstraction <-- Implementor
    RefinedAbstraction o-- Abstraction
    Implementor <|.. ConcreteImplementorA
    Implementor <|.. ConcreteImplementorB

应用场景

Bridge模式适用于以下场景:

  1. 需要在抽象和实现之间存在多维度的变化。例如,一个形状类可能有不同的颜色,使用Bridge模式可以将形状和颜色分别封装,并通过桥梁连接起来。
  2. 需要将抽象和实现解耦,使它们可以独立地变化。例如,一个操作系统可以支持不同的文件系统,使用Bridge模式可以将操作系统和文件系统分别封装。

示例

假设有一个形状类Shape和一个颜色类Color,Shape有不同的派生类(如Circle、Rectangle),Color也有不同的派生类(如Red、Blue)。我们需要将Shape和Color连接起来,以实现不同形状和颜色的组合。

首先,定义Shape的抽象类:

public abstract class Shape {
    protected Color color;
    
    public Shape(Color color) {
        this.color = color;
    }
    
    public abstract void draw();
}

然后,定义Color的抽象类:

public abstract class Color {
    public abstract void fill();
}

接下来,定义具体的Shape类和Color类:

public class Circle extends Shape {
    public Circle(Color color) {
        super(color);
    }
    
    public void draw() {
        System.out.println("Drawing Circle");
        color.fill();
    }
}

public class Rectangle extends Shape {
    public Rectangle(Color color) {
        super(color);
    }
    
    public void draw() {
        System.out.println("Drawing Rectangle");
        color.fill();
    }
}

public class Red extends Color {
    public void fill() {
        System.out.println("Filling with Red color");
    }
}

public class Blue extends Color {
    public void fill() {
        System.out.println("Filling with Blue color");
    }
}

最后,在客户端代码中使用Bridge模式:

public class Client {
    public static void main(String[] args) {
        Shape circleRed = new Circle(new Red());
        Shape rectangleBlue = new Rectangle(new Blue());
        
        circleRed.draw();
        rectangleBlue.draw();
    }
}

输出结果为:

Drawing Circle
Filling with Red color
Drawing Rectangle
Filling with Blue color

序列图

下面是使用序列图表示上述示例的执行过程:

sequenceDiagram
    participant Client
    participant Shape
    participant Circle
    participant Color
    participant Red
    participant Rectangle
    participant Blue
    Client->>+Circle: new Circle(new Red())