重温设计模式 --- 桥接模式

引言

桥接模式是一种结构型设计模式,它可以将一个大类或一组相关的类拆分成抽象和实现两个独立的层次结构,从而可以在两个层次结构中分别变化。桥接模式的核心思想是“尽可能将抽象部分和实现部分分离,使它们可以独立地变化”。这样可以使得系统更加灵活,易于扩展和维护。

在桥接模式中,有两个重要的角色:抽象部分和实现部分。抽象部分定义了一组抽象接口,它们与实现部分相互作用;实现部分则提供了这些接口的具体实现。

实现

  1. 定义抽象部分的接口或抽象类
1
2
3
4
public interface IShape
{
void Draw();
}

2 .定义实现部分的接口或抽象类

1
2
3
4
public interface IColor
{
void Fill();
}
  1. 实现实现部分的具体类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Red : IColor
{
public void Fill()
{
Console.WriteLine("Fill with red color.");
}
}

public class Blue : IColor
{
public void Fill()
{
Console.WriteLine("Fill with blue color.");
}
}
  1. 实现抽象部分的具体类,并在其中包含实现部分的对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public abstract class Shape
{
protected IColor color;

public Shape(IColor color)
{
this.color = color;
}

public abstract void Draw();
}

public class Circle : Shape
{
public Circle(IColor color) : base(color)
{
}

public override void Draw()
{
Console.Write("Draw a circle. ");
color.Fill();
}
}

public class Rectangle : Shape
{
public Rectangle(IColor color) : base(color)
{
}

public override void Draw()
{
Console.Write("Draw a rectangle. ");
color.Fill();
}
}
  1. 客户端调用
1
2
3
4
5
6
7
8
new Red();
IColor blue = new Blue();

Shape circle = new Circle(red);
circle.Draw();

Shape rectangle = new Rectangle(blue);
rectangle.Draw();
  1. 输出:
1
2
with red color.
Draw a rectangle. Fill with blue color.

在上面的代码中,我们定义了两个实现部分的具体类 RedBlue,它们实现了 IColor 接口。然后我们定义了两个抽象部分的具体类 CircleRectangle,并在它们的构造函数中传入一个 IColor 对象,实现了抽象部分和实现部分的解耦。最后,在客户端代码中使用抽象部分,通过传入不同的实现部分对象来实现不同的功能

结论

桥接模式的优点在于它可以让抽象部分和实现部分各自独立地变化,从而可以更加灵活地组合它们。此外,它还可以减少类之间的耦合度,提高代码的可维护性和可扩展性。