概述
桥接模式是一种结构型设计模式,它通过将抽象部分与其实现部分分离,使得两者可以独立地变化。这种模式能够有效应对多维度变化的需求,让系统更加灵活且易于扩展。桥接模式的关键在于定义一个接口(抽象),用来连接两个独立的层次结构:一个是抽象的,另一个是实现的。这样,当实现部分需要变化或者增加新的实现时,不会影响到抽象部分的客户端代码。
目的
在软件开发中,我们经常遇到这样的情况:一个类(或一组类)可能需要在不同的时间点或者环境下,采用不同的实现方式。如果直接将这些实现细节硬编码到抽象类中,将会导致抽象类变得异常复杂,难以维护,并且限制了系统的可扩展性。桥接模式通过将变化的部分(实现细节)从不变的部分(抽象接口)中分离出来,解决了这一问题。
结构
Abstraction(抽象类):定义抽象接口,并包含一个对Implementor(实现者)对象的引用。
Refined Abstraction(修正抽象类):扩展Abstraction,提供具体的操作实现,但这些操作都会委托给Implementor来完成。
Implementor(实现者接口):定义实现类的接口,但不提供具体实现。
Concrete Implementor(具体实现类):实现Implementor接口,提供具体实现。
代码示例
// Implementor(实现者接口)
interface DrawAPI {
void drawCircle(int radius, int x, int y);
}
// Concrete Implementor A
class RedCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: red, radius: " + radius + ", x: " + x + ", y: " + y + "]");
}
}
// Concrete Implementor B
class GreenCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: green, radius: " + radius + ", x: " + x + ", y: " + y + "]");
}
}
// Abstraction
abstract class Shape {
protected DrawAPI drawAPI;
public Shape(DrawAPI drawAPI){
this.drawAPI = drawAPI;
}
abstract void draw();
}
// Refined Abstraction
class Circle extends Shape {
private int x, y, radius;
public Circle(int x, int y, int radius, DrawAPI drawAPI) {
super(drawAPI);
this.x = x;
this.y = y;
this.radius = radius;
}
@Override
public void draw() {
drawAPI.drawCircle(radius, x, y);
}
}
// Client Code
public class BridgePatternDemo {
public static void main(String[ ] args) {
Shape redCircle = new Circle(100, 100, 10, new RedCircle());
Shape greenCircle = new Circle(100, 100, 10, new GreenCircle());
redCircle.draw();
greenCircle.draw();
}
}
适用场景
当一个类存在两个独立变化的维度,且这两个维度都需要进行扩展时。
需要通过不同方式实现同一组接口,且希望客户端能够独立于这组实现时。
避免大量使用多重条件语句(如if-else或switch-case)来选择使用哪种实现方式的情况。
优点
分离抽象与实现:使得抽象和实现可以独立地变化,提高了系统的灵活性和可扩展性。
更好的扩展性:新增实现类或抽象类时,不需要修改现有代码,符合开闭原则。
减少代码重复:相同的实现细节可以被多个抽象类共享,减少了代码量。
缺点
增加了系统的复杂度:引入了额外的抽象和接口,初学者可能会感到困惑。
过度设计的风险:如果系统的变化并不频繁或者复杂度不高,使用桥接模式可能会造成不必要的复杂性。
在这个例子中,DrawAPI
是实现者接口,RedCircle
和GreenCircle
是具体的实现类,Shape
是抽象类,而Circle
是修正抽象类。通过桥接模式,我们可以轻松地为形状添加新的绘制颜色,而无需修改现有的形状类。
评论区