分类: Java
2009-04-01 18:56:41
import java.util.*;
public class MessageApplication {
public void showAllMessage(Enumeration enum) {
Object msg;
while(enum.hasMoreElements()) {
msg = enum.nextElement();
System.out.println(msg);
}
}
}
import java.util.*;
public class MessageClient {
private MessageApplication msgApp;
public void run() {
Vector vector = new Vector();
for(int i = 0; i < 10; i++)
vector.addElement("物件 " + i);
msgApp = new MessageApplication();
msgApp.showAllMessage(vector.elements());
}
public static void main(String[] args) {
MessageClient msgClient = new MessageClient();
msgClient.run();
}
}
import java.util.*;
public class IteratorAdapter implements Enumeration {
private Iterator iterator;
IteratorAdapter(Iterator iterator) {
this.iterator = iterator;
}
// 转接介面
public boolean hasMoreElements() {
return iterator.hasNext();
}
public Object nextElement()
throws NoSuchElementException {
return iterator.next();
}
}
import java.util.*;如程式所示的,透过Adapter模式,您原有程式中已设计好的类别不用更动,就可以引进新类别的功能,将上面的程式UML类别结构画出如下:
public class MessageClient {
// We could still use MessageApplication
private Enumeration iteratorAdapter;
public void run() {
List arrayList = new ArrayList();
for(int i = 0; i < 10; i++)
arrayList.add("物件 " + i);
iteratorAdapter =
new IteratorAdapter(arrayList.iterator());
// We could still use MessageApplication
MessageApplication msgApp = new MessageApplication();
msgApp.showAllMessage(iteratorAdapter);
}
public static void main(String[] args) {
MessageClient msgClient = new MessageClient();
msgClient.run();
}
}