import java.util.ArrayList;
import java.util.Collection;
interface Visitor{
public void visitElementA(ConcreteElementA elementA);//针对具体元素A的新方法
public void visitElementB(ConcreteElementB elementB);//针对具体元素B的新方法
}
interface Element{
public void accept(Visitor visitor);
}
class ConcreteVisitor implements Visitor{//具体的访问者
public void visitElementA(ConcreteElementA elementA) {
System.out.println(elementA.getName()+" visited by ConcreteVisitor ");
}
public void visitElementB(ConcreteElementB elementB) {
System.out.println(elementB.getName()+" visited by ConcreteVisitor ");
}
}
class ConcreteElementA implements Element{//具体元素A
private String name;
public ConcreteElementA(String name){
this.name=name;
}
public void accept(Visitor visitor) {//接受访问者调用它针对该元素的新方法
visitor.visitElementA(this);
}
public String getName() {
return name;
}
}
class ConcreteElementB implements Element{//具体元素B
private String name;
public ConcreteElementB(String name){
this.name=name;
}
public String getName() {
return name;
}
public void accept(Visitor visitor) {//接受访问者调用它针对该元素的新方法
visitor.visitElementB(this);
}
}
class ObjectStructure{//对象结构即元素的集合
private Collection<Element> collection=new ArrayList<Element>();
public void attach(Element element){
collection.add(element);
}
public void detach(Element element){
collection.remove(element);
}
public void accept(Visitor visitor )
{
for(Element element:collection){
element.accept(visitor);
}
}
}
public class Client {
public static void main(String args[]){
Element elementA=new ConcreteElementA("ElementA");
Element elementB=new ConcreteElementB("ElementB");
Visitor visitor=new ConcreteVisitor();
ObjectStructure os=new ObjectStructure();
os.attach(elementA);
os.attach(elementB);
os.accept(visitor);
}
}
Visitor模式
最新推荐文章于 2020-05-05 08:20:34 发布