"Bridge" 设计模式应该如何实现超过两个层次结构?

How should a "Bridge" design pattern be implemented for more than two hierarchies?

这解释了我所指的“桥接”模式:https://refactoring.guru/design-patterns/bridge

这是上面 post 中的一个场景:

Say you have a geometric Shape class with a pair of subclasses: Circle and Square. You want to extend this class hierarchy to incorporate colors, so you plan to create Red and Blue shape subclasses. However, since you already have two subclasses, you’ll need to create four class combinations such as BlueCircle and RedSquare.

这个场景出现的问题:

Adding new shape types and colors to the hierarchy will grow it exponentially. For example, to add a triangle shape you’d need to introduce two subclasses, one for each color. And after that, adding a new color would require creating three subclasses, one for each shape type. The further we go, the worse it becomes.

为了避免这个问题,我们实现桥接模式是这样的:

Extract the color-related code into its own class with two subclasses: Red and Blue. The Shape class then gets a reference field pointing to one of the color objects. Now the shape can delegate any color-related work to the linked color object. That reference will act as a bridge between the Shape and Color classes. From now on, adding new colors won’t require changing the shape hierarchy, and vice versa.

我理解这个实现的方式和原因。

但是如果我们需要第三层级呢? BorderStyle(边框样式可以是 StraightWavyZigZag?)

我想我们可以为 BorderStyle 实现第二个 Implementor class 并将其传递给 Shape 构造函数,如下所示:

# Blue inherits from the Color class (Implementation)
color_implementation = Blue.new()

# Wavy inherits from the BorderStyle class (Implementation)
border_style_implementation = Wavy.new()

# Triangle inherits from the Shape class, which we consider our Abstraction
shape = Triangle.new(color_implementation, border_style_implementation)

shape.draw() # prints "I'm a Blue Triangle with Wavy borders!"

所以我的问题是:

1.) 上面的例子“行得通”吗? (也许它是工作代码,但它是否以某种方式引入了技术债务?)

1a.) 如果这不起作用,为什么不呢?

1b.) 如果这确实“有效”,那么它是否是桥接模式的正确应用?是否有更好的设计模式可用于管理超过 2 个 hierarchies/properties(考虑装饰器模式?)

如果我遗漏了任何相关信息,我深表歉意——这种设计模式对我来说是全新的。感谢您的帮助!

是的,这行得通。将两个 Bridge 关系添加到一个抽象中并没有错(除了处理三个不同层次结构的复杂性之外)。

Decorator 肯定不会用于此目的,因为它维护一个客户知道的单一层次结构。客户端不知道 Bridge 中的 Implementor 层次结构(或本例中的层次结构)。

我会澄清链接的文章,它说,

You want to extend this [shape] class hierarchy to incorporate colors

我认为这过度简化了 Bridge 的动机。 Implementor 不仅仅是您选择添加到 Abstraction 以增强它的一些属性。您的 Abstraction 需要 Implementor 才能正常运行。 Abstraction 的子类中的方法实现通常做的很少,除了 Implementor.

的调用方法

Abstraction代表您的高级业务API,而Implementor代表较低级别的原始业务API。它们都是抽象的,但处于不同的层次。我认为形状和颜色的例子并不能充分表达这一点,因为形状和颜色看起来像是同一层次的抽象。形状和颜色都会被客户知道,两者都严格依赖于另一个。

所以应用 Bridge 的原因比给出的示例更具体,但您当然可以有两个。