从集合类的升级联想到Java适配器模式2007-04-20 来自:java060515  [收藏到我的网摘]
Historical Collection Classes(JDK1.1 之前)
提供的容器有Arrays,Vector,Stack,Hashtable,Properties,BitSet。其中定义出一种走访群集内各元素的标准方式,称为Enumeration(列举器)接口,用法如下:
Vector v=new Vector(); 
for (Enumeration enum =v.elements(); enum.hasMoreElements(); ) {
Object o = enum.nextElement(); 
processObject(o); 
}
而在JDK1.2版本中引入了Iterator接口,新版本的集合对象(HashSet,HashMap,WeakHeahMap,ArrayList,TreeSet,TreeMap, LinkedList)是通过Iterator接口访问集合元素的。
例如: List list=new ArrayList(); 
for(Iterator it=list.iterator(); it.hasNext(); )
{
System.out.println(it.next()); 
}
这样,如果将老版本的程序运行在新的Java编译器上就会出错。因为List接口中已经没有elements(),而只有iterator()了。那么如何可以使老版本的程序运行在新的Java编译器上呢?如果不加修改,是肯定不行的,但是修改要遵循“开-闭”原则。
这时候我想到了Java设计模式中的适配器模式。
/**//*
*@author 我为J狂 建立日期 2007-4-18
*
*/
package net.blogjava.lzqdiy; 
import java.util.ArrayList; 
import java.util.Enumeration; 
import java.util.Iterator; 
import java.util.List; 
public class NewEnumeration implements Enumeration
{
Iterator it; 
public NewEnumeration(Iterator it)
{
this.it=it; 
// TODO Auto-generated constructor stub
}
public boolean hasMoreElements()
{
// TODO Auto-generated method stub
return it.hasNext(); 
}
public Object nextElement()
{
// TODO Auto-generated method stub
return it.next(); 
}
public static void main(String[] args)
{
List list=new ArrayList(); 
list.add("a"); 
list.add("b"); 
list.add("C"); 
for(Enumeration e=new NewEnumeration(list.iterator()); e.hasMoreElements(); )
{
System.out.println(e.nextElement()); 
}
}
}
NewEnumeration是一个适配器类,通过它实现了从Iterator接口到Enumeration接口的适配,这样我们就可以使用老版本的代码来使用新的集合对象了。
	posted on 2007-04-22 09:23 
happytian 阅读(296) 
评论(0)  编辑  收藏