一 概要
1.1 结构型模式
- 关注类和对象的组合。继承的概念被用来组合接口和定义组合对象,从而获得新功能。
1.2 定义
- 将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类能一起工作。适配器模式分为类结构型模式和对象结构型模式两种,前者类之间的耦合度比后者高,且要求程序员了解现有组件库中的相关组件的内部结构,所以应用相对较少些。
二 对象适配器
2.1 UML类图
2.2 例子
class Program
{
static void Main(string[] args)
{
Target target = new Adapter();
target.Request();
}
}
public interface Target
{
void Request();
}
public class Adapter: Target
{
private Adaptee adaptee = new Adaptee();
public void Request()
{
adaptee.RealRequest();
}
}
public class Adaptee
{
public void RealRequest()
{
}
}
2.3 优缺点
2.3.1 优点
- 可以让任何两个没有关联的类一起运行。
- 可以在不修改原有代码的基础上来复用现有类。
2.3.2 缺点
- 过多地使用适配器,会让系统非常零乱,不易整体进行把握。
三 类适配器
3.1 UML类图
3.2 例子
class Program
{
static void Main(string[] args)
{
ITarget target = new Adapter();
target.Request();
}
}
public interface ITarget
{
void Request();
}
public class Adaptee
{
public void RealReuest()
{
}
}
public class Adapter : Adaptee, ITarget
{
public void Request()
{
this.RealReuest();
}
}
3.3 优缺点
3.3.1 优点
- 符合开放封闭原则,在子类 Adapter 中扩展了 需要适配的类 Adaptee 的 部分行为,Adaptee内部不需要做出任何修改, 使之能满足了客户端的需求。
3.3.2 缺点
- 使用了继承的方式,耦合高。
四 类适配器与对象适配器的区别
- 类适配器采用了继承的方式实现适配, 对象适配器采用的组合的方式适配。
五 使用场景
- 以前开发的系统存在满足新系统功能需求的类,但其接口同新系统的接口不一致。
- 使用第三方提供的组件,但组件接口定义和自己要求的接口定义不同。