适配器模式是一种结构型设计模式,用于将一个类的接口转换成客户端所期待的另一个接口,使得原本由于接口不兼容而不能在一起工作的类能够协同工作。这种模式通常用于软件系统的升级和重构中,可以使得原有的代码能够与新的接口相兼容,同时不改变原有代码的情况下实现功能的更新和扩展。
优点:
缺点:
适用场景:
假设有一个旧的接口 IOldInterface,而客户端希望使用新的接口 INewInterface,但两者的方法不兼容,可以通过适配器模式来解决:
// 旧的接口
public interface IOldInterface
{
void OldMethod();
}
// 新的接口
public interface INewInterface
{
void NewMethod();
}
// 旧接口的实现类
public class OldClass : IOldInterface
{
public void OldMethod()
{
Console.WriteLine("Old method is called");
}
}
// 适配器类,将旧的接口适配成新的接口
public class Adapter : INewInterface
{
private readonly IOldInterface _oldClass;
public Adapter(IOldInterface oldClass)
{
_oldClass = oldClass;
}
public void NewMethod()
{
// 在新方法中调用旧接口的方法
_oldClass.OldMethod();
}
}
// 客户端代码
class Program
{
static void Main(string[] args)
{
// 创建旧接口的实例
IOldInterface oldClass = new OldClass();
// 创建适配器,将旧接口适配成新接口
INewInterface adapter = new Adapter(oldClass);
// 客户端调用新接口的方法
adapter.NewMethod(); // 实际上调用的是旧接口的方法
}
}
Adapter 类充当了适配器的角色,将旧接口 IOldInterface 适配成了新接口 INewInterface,使得客户端可以通过调用新接口的方法来间接调用旧接口的方法。