名称:Adapter
结构:

意图:
将一个类的接口转换成客户希望的另外一个接口。A d a p t e r 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
适用性 :
- 你想使用一个已经存在的类,而它的接口不符合你的需求。
- 你想创建一个可以复用的类,该类可以与其他不相关的类或不可预见的类(即那些接口可能不一定兼容的类)协同工作。
- 你想使用一些已经存在的子类,但是不可能对每一个都进行子类化以匹配它们的接口。对象适配器可以适配它的父类接口。
示例代码:
// Adapter
namespace Adapter_DesignPattern
{
using System;
class FrameworkXTarget
{
virtual public void SomeRequest(int x)
{
// normal implementation of SomeRequest goes here
}
}
class FrameworkYAdaptee
{
public void QuiteADifferentRequest(string str)
{
Console.WriteLine("QuiteADifferentRequest = {0}", str);
}
}
class OurAdapter : FrameworkXTarget
{
private FrameworkYAdaptee adaptee = new FrameworkYAdaptee();
override public void SomeRequest(int a)
{
string b;
b = a.ToString();
adaptee.QuiteADifferentRequest(b);
}
}
/// <summary>
/// Summary description for Client.
/// </summary>
public class Client
{
void GenericClientCode(FrameworkXTarget x)
{
// We assume this function contains client-side code that only
// knows about FrameworkXTarget.
x.SomeRequest(4);
// other calls to FrameworkX go here
// ...
}
public static int Main(string[] args)
{
Client c = new Client();
FrameworkXTarget x = new OurAdapter();
c.GenericClientCode(x);
return 0;
}
}
}
namespace Adapter_DesignPattern
{
using System;
class FrameworkXTarget
{
virtual public void SomeRequest(int x)
{
// normal implementation of SomeRequest goes here
}
}
class FrameworkYAdaptee
{
public void QuiteADifferentRequest(string str)
{
Console.WriteLine("QuiteADifferentRequest = {0}", str);
}
}
class OurAdapter : FrameworkXTarget
{
private FrameworkYAdaptee adaptee = new FrameworkYAdaptee();
override public void SomeRequest(int a)
{
string b;
b = a.ToString();
adaptee.QuiteADifferentRequest(b);
}
}
/// <summary>
/// Summary description for Client.
/// </summary>
public class Client
{
void GenericClientCode(FrameworkXTarget x)
{
// We assume this function contains client-side code that only
// knows about FrameworkXTarget.
x.SomeRequest(4);
// other calls to FrameworkX go here
// ...
}
public static int Main(string[] args)
{
Client c = new Client();
FrameworkXTarget x = new OurAdapter();
c.GenericClientCode(x);
return 0;
}
}
}