package Visitor.MyTest;
import java.util.Collection;
import java.util.Iterator;
/**
* 采访者
* @author Administrator
*/
public abstract class Visitor {
public void visit(Visitable visitable) {
// TODO Auto-generated method stub
System.out.println(this+"采访了"+visitable);
}
public void visitCollection(Collection collection)
{
Iterator it=collection.iterator();
while(it.hasNext())
{
Object obj=it.next();
if(obj instanceof Visitable)
{
System.out.println(this+"采访了"+obj);
}
}
};
public abstract String toString();
}
package Visitor.MyTest;
/**
* 被采访者
* @author Administrator
*
*/
public abstract class Visitable {
/** 接受采访者的采访 **/
public abstract void accept(Visitor visitor);
}
package Visitor.MyTest;
public class Visitable1 extends Visitable {
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "被采访者甲";
}
}
package Visitor.MyTest;
public class Visitable2 extends Visitable {
@Override
public void accept(Visitor visitor) {
// TODO Auto-generated method stub
visitor.visit(this);
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "被采访者乙";
}
}
package Visitor.MyTest;
public class Visitable3 extends Visitable {
@Override
public void accept(Visitor visitor) {
// TODO Auto-generated method stub
visitor.visit(this);
}
@Override
public String toString() {
return "被采访者丙";
}
}
package Visitor.MyTest;
public class VisitorA extends Visitor{
@Override
public String toString() {
return "记者A";
}
}
package Visitor.MyTest;
public class VisitorB extends Visitor{
@Override
public String toString() {
return "记者B";
}
}
package Visitor.MyTest;
import java.util.ArrayList;
import java.util.Collection;
public class MyTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Visitable vb1=new Visitable1();
Visitable vb2=new Visitable2();
Visitable vb3=new Visitable3();
Visitor vsa=new VisitorA();
Visitor vsb=new VisitorB();
vb1.accept(vsa);
vsa.visit(vb3);
Collection c=new ArrayList();
c.add("xx");
c.add(vsb);
c.add(vb2);
vsb.visitCollection(c);
}
}