2009年10月8日星期四

Adapter适配器设计模式

在代理设计模式中,类A中要对外提供一些功能(公开接口),但是类A中有些功能不能自己实现,于是就创建一个类B的实例b,将处理交给b中的公开函数去处理,实现了A代理B,目的是给调用者提供统一的接口,这就是代理设计模式。
在Adapter的设计模式中,假设用户需要调用接口 I 来实现某种功能,系统S可以提供这种功能但是接口和用户要求的不一致。就要创建一个Adapter类用系统S提供的功能来重写接口I,这就是Adapter设计模式。因为是将系统S的功能用接口I来包装,所以也叫做Wrapper模式。这种模式适用于接口已经定义好了,功能需要调用别的系统实现的情况。
例如:设计一套电子支付系统,通过银行的接口访问已支付客户名单。接口已经定义好,返回客户名单是一个用逗号分隔好的字符串。

public interface IGateway
{
string GetCSVCustomers();
}

后来调查银行提供的API接口,返回用户是一个List序列,和希望的接口不一致。

public class MoolahGateway
{
public List GetCustomers()
{
List listCustomers = new List();

listCustomers.Add("Bob Smith");
listCustomers.Add("Chris Thomas");
listCustomers.Add("Dave Mathews");

return listCustomers;
}
}

为了让银行提供的接口和希望的接口一直,对银行的接口实行适配或者说包装。我们创建一个类,重写接口IGateway。

public class MoolahGatewayAdapter : IGateway
{
private MoolahGateway _moolahGateway = new MoolahGateway();

string IGateway.GetCSVCustomers()
{
List listCustomers = _moolahGateway.GetCustomers();
StringBuilder csvCustomers = new StringBuilder();

foreach (string item in listCustomers)
{
csvCustomers.Append(item);
csvCustomers.Append(",");
}

return csvCustomers.ToString().TrimEnd(',');
}
}

现在MoolahGatewayAdapter 提供的接口满足要求了。

class Program
{
static void Main(string[] args)
{
IGateway gateway = new MoolahGatewayAdapter();

Console.WriteLine(gateway.GetCSVCustomers());
}
}

执行结果:
Bob Smith,Chris Thomas,Dave Mathews

没有评论:

发表评论