意图:
将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
Target定义一个目标接口,可以是一个接口也可以是一个抽象类.
Adapter适配器类,它要实现目标接口且维护一个被适配对象的实例.
Adaptee被适配对象
Client客户端调用
很典型的例子就是笔记本电脑的电源适配器,它通过适配器将直流电转化为笔记本电脑所需的标准电压.
class Program
{
static void Main(string[] args)
{
ITarget t = new Adapter(new Adaptee());
t.WriteEvent(DateTime.Now.ToString());
Console.Read();
}
}
/// <summary>
/// 目标接口
/// </summary>
interface ITarget
{
void WriteEvent(string msg);
}
/// <summary>
/// 适配器类,它要实现目标接口且维护一个被适配对象的实例
/// </summary>
class Adapter : ITarget
{
Adaptee adaptee;
public Adapter(Adaptee a)
{
adaptee = a;
}
/// <summary>
/// 实现目标接口的方法,将它委托给被适配对象去执行,而这一切对客户来说是解耦的
/// </summary>
/// <param name="msg"></param>
public void WriteEvent(string msg)
{
adaptee.AdapteeWrite(msg);
}
}
/// <summary>
/// 被适配对象
/// </summary>
class Adaptee
{
public void AdapteeWrite(string msg)
{
Console.WriteLine("这里适配器在起作用:"+msg);
}
}
适配器模式又分为对象适配与类适配,对象适配通过组合实现,如上面的例子.类适配通过继承来实现.
输出结果