概述
Adapter模式又叫适配器(变压器)模式:把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口原因不匹配而无法一起工作的两个类能够一起工作。适配类可以根据参数返还一个合适的实例给客户端。
设计
那么是如何“适配”的呢?比如,东西A想使用东西B,但是A无法使用B,怎么办?A就让东西C帮忙,A通过C就可以用B了。其实A、B就好像是两节水管,C就好像是连接水管的接头。
实现
UML图:
标准示例:
1
// Adapter
2
3
// Intent: "Convert the interface of a class into another interface
4
// clients expect. Adapter lets classes work together that couldn't
5
// otherwise because of incompatible interfaces".
6
7
// For further information, read "Design Patterns", p139, Gamma et al.,
8
// Addison-Wesley, ISBN:0-201-63361-2
9
10
2
3
4
5
6
7
8
9
10
示例代码为:
1
using System;
2
3
namespace Example
4
2
3
4
同样的方法我们来解决中国人和英国人对话的问题:
1
namespace DesignPattern.Template
2
}
2