The Bridge Pattern in Java – Java中的桥接模式

最后修改: 2019年 11月 10日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

The official definition for the Bridge design pattern introduced by Gang of Four (GoF) is to decouple an abstraction from its implementation so that the two can vary independently.

四人帮(Gang of Four,GoF)引入的桥接设计模式的官方定义是将一个抽象与其实现解耦,以便两者可以独立变化。

This means to create a bridge interface that uses OOP principles to separate out responsibilities into different abstract classes.

这意味着要创建一个桥梁接口,使用OOP原则将责任分离到不同的抽象类中。

2. Bridge Pattern Example

2.桥模式实例

For the Bridge pattern, we’ll consider two layers of abstraction; one is the geometric shape (like triangle and square) which is filled with different colors (our second abstraction layer):

对于桥梁图案,我们将考虑两个抽象层;一个是几何形状(如三角形和方形),它被不同的颜色填充(我们的第二个抽象层)。

Bridge Pattern

First, we’ll define a color interface:

首先,我们要定义一个颜色接口。

public interface Color {
    String fill();
}

Now we’ll create a concrete class for this interface:

现在我们要为这个接口创建一个具体的类。

public class Blue implements Color {
    @Override
    public String fill() {
        return "Color is Blue";
    }
}

Let’s now create an abstract Shape class which consists a reference (bridge) to the Color object:

现在让我们创建一个抽象的Shape类,它包括对Color对象的引用(桥梁)。

public abstract class Shape {
    protected Color color;
    
    //standard constructors
    
    abstract public String draw();
}

We’ll now create a concrete class of Shape interface which will utilize method from Color interface as well:

我们现在将创建一个形状界面的具体类,它也将利用颜色界面的方法。

public class Square extends Shape {

    public Square(Color color) {
        super(color);
    }

    @Override
    public String draw() {
        return "Square drawn. " + color.fill();
    }
}

For this pattern, the following assertion will be true:

对于这种模式,以下断言将是真的。

@Test
public void whenBridgePatternInvoked_thenConfigSuccess() {
    //a square with red color
    Shape square = new Square(new Red());
 
    assertEquals(square.draw(), "Square drawn. Color is Red");
}

Here, we’re using the Bridge pattern and passing the desired color object. As we can note in the output, the shape gets draws with the desired color:

在这里,我们使用Bridge模式并传递所需的颜色对象。正如我们在输出中注意到的那样,形状被绘制成了所需的颜色。

Square drawn. Color: Red
Triangle drawn. Color: Blue

3. Conclusion

3.结论

In this article, we had a look at the bridge design pattern. This is a good choice in the following cases:

在这篇文章中,我们看了一下桥梁设计模式。在以下情况下,这是一个不错的选择。

  • When we want a parent abstract class to define the set of basic rules, and the concrete classes to add additional rules
  • When we have an abstract class that has a reference to the objects, and it has abstract methods that will be defined in each of the concrete classes

The full source code for this example is available over on GitHub.

这个例子的完整源代码可以在GitHub上找到