算法和数据结构分开__访问者模式___Visitor

packagecom.ding.shejimoshi.Visitor;

abstractclassVisitor{

publicabstractvoidvisitConcreteElementA(ConcreteElementAconcreteElementA);

publicabstractvoidvisitConcreteElementB(ConcreteElementBconcreteElementB);

}

packagecom.ding.shejimoshi.Visitor;

publicclassConcreteVisitor1extendsVisitor{

publicvoidvisitConcreteElementA(ConcreteElementAconcreteElementA){

System.out.println(concreteElementA.getClass()+"被"+this.getClass()+"访问");

}

publicvoidvisitConcreteElementB(ConcreteElementBconcreteElementB){

System.out.println(concreteElementB.getClass()+"被"+this.getClass()+"访问");

}

}

packagecom.ding.shejimoshi.Visitor;

publicclassConcreteVisitor2extendsVisitor{

publicvoidvisitConcreteElementA(ConcreteElementAconcreteElementA){

System.out.println(concreteElementA.getClass()+"被"+this.getClass()+"访问");

}

publicvoidvisitConcreteElementB(ConcreteElementBconcreteElementB){

System.out.println(concreteElementB.getClass()+"被"+this.getClass()+"访问");

}

}

packagecom.ding.shejimoshi.Visitor;

abstractclassElement{

publicabstractvoidaccept(Visitorvisitor);

}

packagecom.ding.shejimoshi.Visitor;

publicclassConcreteElementAextendsElement{

publicvoidaccept(Visitorvisitor){

visitor.visitConcreteElementA(this);

}

}

packagecom.ding.shejimoshi.Visitor;

publicclassConcreteElementBextendsElement{

publicvoidaccept(Visitorvisitor){

visitor.visitConcreteElementB(this);

}

}

packagecom.ding.shejimoshi.Visitor;

importjava.util.ArrayList;

importjava.util.List;

publicclassObjectStructure{

privateList<Element>elements=newArrayList<Element>();

publicvoidattace(Elementelement){

elements.add(element);

}

publicvoiddetach(Elementelement){

elements.remove(element);

}

publicvoidaccept(Visitorvisitor){

for(Elements:elements){

s.accept(visitor);

}

}

}

packagecom.ding.shejimoshi.Visitor;

publicclassMain{

publicstaticvoidmain(String[]args){

ObjectStructureo=newObjectStructure();

o.attace(newConcreteElementA());

o.attace(newConcreteElementB());

ConcreteVisitor1v1=newConcreteVisitor1();

ConcreteVisitor2v2=newConcreteVisitor2();

o.accept(v1);

o.accept(v2);

}

}

----------------------------------------------------------------------------------------------------

classcom.ding.shejimoshi.Visitor.ConcreteElementA被classcom.ding.shejimoshi.Visitor.ConcreteVisitor1访问

classcom.ding.shejimoshi.Visitor.ConcreteElementB被classcom.ding.shejimoshi.Visitor.ConcreteVisitor1访问

classcom.ding.shejimoshi.Visitor.ConcreteElementA被classcom.ding.shejimoshi.Visitor.ConcreteVisitor2访问

classcom.ding.shejimoshi.Visitor.ConcreteElementB被classcom.ding.shejimoshi.Visitor.ConcreteVisitor2访问

-------------------------------------------------------------------------------------------------------

访问者模式优点数据结构和算法分开

缺点不要增加新的数据结构

-----------------------------------------------------------------------------------------------------------

privateList<Element>elements=newArrayList<Element>();

类的集合

相关推荐