class Home {private List<Animal> nodeList = new ArrayList<>();void action(Person person) { for (Animal node : nodeList) { node.accept(person); }}/** * 添加操纵 * * @param animal 动物 */void add(Animal animal) { nodeList.add(animal);}}
创建客户端,用于测试
public class Client {public static void main(String[] args) { Home home = new Home(); home.add(new Dog()); home.add(new Cat()); Owner owner = new Owner(); home.action(owner); Someone someone = new Someone(); home.action(someone);}}
public abstract class Element { public abstract void accept(Visitor visitor);}
具体元素
public class ConcreteElementA extends Element {@Overridepublic void accept(Visitor visitor) { visitor.visitConcreteElementA(this);}public String operationA() { return "ConcreteElementA";}}public class ConcreteElementB extends Element {@Overridepublic void accept(Visitor visitor) { visitor.visitConcreteElementB(this);}public String operationB() { return "ConcreteElementB";}}
对象结构角色
public class ObjectStructure {private List<Element> elments = new LinkedList<Element>();// 新增public void attach(Element element) { elments.add(element);}// 删除public void detach(Element element) { elments.remove(element);}public void accept(Visitor visitor) { for (Element elment:elments ) { elment.accept(visitor); }}}
测试类
public class Test {public static void main(String[]args) { ObjectStructure o = new ObjectStructure(); o.attach(new ConcreteElementA()); o.attach(new ConcreteElementB()); ConcreteVisitor1 concreteVisitor1 = new ConcreteVisitor1(); ConcreteVisitor2 concreteVisitor2 = new ConcreteVisitor2(); o.accept(concreteVisitor1); o.accept(concreteVisitor2);}}