定义:
定义一个访问者,去访问集合中不同类型的对象;集合中的每个对象都被定义成被访问者
要点:
集合中的每个对象都必须符合被访问者规范
实例:
1.定义被访问者行为规范
public interface Visible {
public void accept( Visitor visitor ) throws Exception;
}
2.定义被访问者类型,这里定义了string和int两种类型
public class IntegerElement implements Visible {
private final Integer value;
public IntegerElement( Integer value ){
this.value = value;
}
public Integer getValue(){
return value;
}
@Override
public void accept(Visitor visitor) throws Exception {
// TODO Auto-generated method stub
visitor.visitIntegerElement(this);
}
}
public class StringElement implements Visible{
private final String value;
public StringElement( String value ){
this.value = value;
}
public String getValue(){
return value;
}
@Override
public void accept(Visitor visitor) throws Exception {
// TODO Auto-generated method stub
visitor.visitStringElement(this);
}
}
3.定义访问者规范
import java.util.Collection;
public interface Visitor {
@SuppressWarnings("rawtypes")
public void visitCollectionElement(Collection collection) throws Exception;
public void visitIntegerElement(IntegerElement integerElement);
public void visitStringElement(StringElement stringElement);
}
4.定义访问者类型
import java.util.Collection;
import java.util.Iterator;
public class DefaultVisitorImpl implements Visitor {
@Override
public void visitIntegerElement(IntegerElement integerElement) {
// TODO Auto-generated method stub
System.out.println(integerElement.getValue().intValue());
}
@Override
public void visitStringElement(StringElement stringElement) {
// TODO Auto-generated method stub
System.out.println(stringElement.getValue());
}
@SuppressWarnings("rawtypes")
@Override
public void visitCollectionElement(Collection collection) throws Exception {
if( collection != null && !collection.isEmpty()){
Iterator iterator = collection.iterator();
while( iterator.hasNext() ){
Visible visibleObj = (Visible)iterator.next();
visibleObj.accept(this);
}
}
}
}
5.测试
import java.util.ArrayList;
import java.util.List;
public class Test {
/**
* @param args
* @throws Exception
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) throws Exception {
StringElement se = new StringElement("string");
IntegerElement ie = new IntegerElement(3);
List list = new ArrayList();
list.add(se);
list.add(ie);
Visitor visitor = new DefaultVisitorImpl();
visitor.visitCollectionElement(list);
}
}