适配器模式

in Develop

意图:
将一个类的接口转换成客户希望的另外一个接口。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);
}
}

适配器模式又分为对象适配与类适配,对象适配通过组合实现,如上面的例子.类适配通过继承来实现.

输出结果

2 Comments

2 Comments

  1. 先来学习一下,最近准备开始多看看.NET方面的学习书了,到时候还希望能多向 幻想曲你请教一下的!^_^

  2. 嗯哈
    共同学习

Leave a Reply

Using Gravatars in the comments - get your own and be recognized!

XHTML: These are some of the tags you can use: <a href=""> <b> <blockquote> <code> <em> <i> <strike> <strong>