Bridge
Bridge prevents a 'Cartesian Product
' complexity explosion. When two hierarchies needs to be combined, we will finally generate a massive combinations just like Cartesian Product
. Bridge Pattern
is to bridge two hierarchies that ensures the encapsulation, the complexity of our code.
Example
The first hierarchy of IRenderer
.
cs
interface IRenderer
{
void Render(double area);
}
class VectorRenderer : IRenderer
{
public void Render(double area) => Console.WriteLine($"Rendering using {nameof(VectorRenderer)} with area:{area}");
}
class RasterRenderer : IRenderer
{
public void Render(double area) => Console.WriteLine($"Rendering using {nameof(RasterRenderer)} with area:{area}");
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
And the second hierarchy of Shape
.
cs
abstract class Shape
{
protected IRenderer renderer;
protected Shape(IRenderer renderer) => this.renderer = renderer;
public abstract void Draw();
}
class Rectangle(double width, double height, IRenderer renderer) : Shape(renderer)
{
protected double width = width;
protected double height = height;
public override void Draw() => renderer.Render(width * height);
}
class Circle(double radius, IRenderer renderer) : Shape(renderer)
{
protected double radius = radius;
public override void Draw() => renderer.Render(radius * radius * Math.PI);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Now we see, Shape
is dependent on IRenderer
to render itself. In this scenario, IRenderer
is the bridge that connects two hierarchies though it is the head of one hierarchy. This approach avoids generating massive classes like
cs
class RectangleWithVectorRenderer(VectorRenderer renderer) { ... }
class RectangleWithRasterRenderer(RasterRenderer renderer) { ... }
class CircleWithVectorRenderer(VectorRenderer renderer) { ... }
class CircleWithRasterRenderer(RasterRenderer renderer) { ... }
1
2
3
4
2
3
4
That's it!