C#中的适配器模式

适配器模式:将一个类的接口转换成客户希望的另外一个接口,即接口转换的桥梁。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
///<适配器模式>
public interface ITarget
{
void Request();
}
public class Adaptee
{
public void SpecificRequest()
{
Console.WriteLine("Adaptee.SpecificRequest is called");
}
}
public class Adapter : ITarget
{
private Adaptee _adaptee = new Adaptee();
public void Request()
{
_adaptee.SpecificRequest();
}
}

///<适配器模式/>

执行流程:

  1. 客户端调用适配器Request()方法
  2. 适配器调用被适配者Adaptee.SpecificRequest()方法
    1
    2
    3
    // 客户端调用
    ITarget target = new Adapter();
    target.Request();
    模式结构
    角色 代码示例 职责
    目标接口 ITarget 定义客户端使用的统一接口
    适配者 Adaptee 需要被适配的现有类
    适配器 Adapter 实现目标接口并包装适配者

关键点

1
2
3
4
5
6
7
public class Adapter : ITarget {
private Adaptee _adaptee = new Adaptee(); // 1. 持有适配者实例

public void Request() { // 2. 实现目标接口方法
_adaptee.SpecificRequest(); // 3. 委托给适配者的方法
}
}

工作流程:

  1. 客户端调用目标接口方法 Request()

  2. 适配器将调用转发给适配者的 SpecificRequest()

  3. 适配者执行实际功能

应用场景

  • 集成不兼容的第三方库

  • 复用遗留系统功能

  • 统一多个类的接口

  • 系统升级时的接口转换

优势

  • 接口兼容:使不兼容接口能协同工作

  • 复用性:无需修改现有代码即可重用功能

  • 解耦:客户端与适配者无直接依赖

要点记忆

  1. Adapter 类实现 ITarget 接口

  2. 适配器内部持有 Adaptee 实例

  3. Request() 方法中调用 SpecificRequest()

  4. 客户端只与 ITarget 接口交互

完整代码

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
///<适配器模式>
public interface ITarget
{
void Request();
}
public class Adaptee
{
public void SpecificRequest()
{
Console.WriteLine("Adaptee.SpecificRequest is called");
}
}
public class Adapter : ITarget
{
private Adaptee _adaptee = new Adaptee();
public void Request()
{
_adaptee.SpecificRequest();
}
}

///<适配器模式/>


public class Program
{
public static void Main(string[] args)
{
///<适配器模式>
Console.WriteLine();
Console.WriteLine("适配器模式:");
ITarget adapter = new Adapter();
adapter.Request();
///<适配器模式/>
}
}