上一节我们讲了迭代器Iterator模式
http://www.cnblogs.com/lee22536973/archive/2008/07/28/1254192.html
这一节我们要讲一个适配器Adapter模式
适配器模式比较好理解,好比一个220v交流电可以用一个交流电适配器转化成直流12v供笔记本使用一样。
程序也比较简单。一般是通过继承的方式进行。
我们以一个字符串处理为例子:
现在有一个已经有的旧的字符串类叫做PrintOld
定义如下:
public class PrintOld
{
public string AddStar(string words)
{
return "*" + words + "*";
}
}
很容易看懂,AddStar()函数的作用就是把字符串的两边加上“*”号。
现在公司要求写一个新的打印接口,用于升级用,并要求名字叫做PrintNew,结构已经定义好,作用仍然是把字符串的两边加上“*”号。
定义如下:
public interface PrintNew
{
string Show(string words);
}
这种需求一出来,我们自然就会想到能不能重用以前的PrintOld呢?
我们当然可以用copy的方法,但是面对更现实的问题的时候,适配器模式这时就起作用了。
ok,下面来看看我们的适配器的定义,是他将PrintOld和PrintNew两个联合起来。
public class PrintAdapter : PrintOld , PrintNew
{
public string Show(string words)
{
return AddStar(words);
}
}
PrintAdapter既继承了PrintOld ,又继承了PrintNew,这样就能对他们做一种转换。
用main函数做测试:
static void Main(string[] args)
{
PrintNew p = new PrintAdapter();
System.Console.WriteLine(p.Show("Hello,Adapter!"));
System.Console.ReadLine();
}
输出是:
*Hello,Adapter!*
写程序并不是每次都要从0出发,我们经常会利用一些既有的类,适配器模式可以帮助你节约建立必要方法的时间。