标签:visitor get 一个 string ide com nta static simple
访问者模式:表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。
public interface Visitor { public void visitElementA(ConcreteElementA concreteElementA); public void visitElementB(ConcreteElementB concreteElementB); }
public class ConcreteVisitorOne implements Visitor { @Override public void visitElementA(ConcreteElementA concreteElementA) { System.out.println(this.getClass().getSimpleName() + "访问" + concreteElementA.getClass().getSimpleName()); } @Override public void visitElementB(ConcreteElementB concreteElementB) { System.out.println(this.getClass().getSimpleName() + "访问" + concreteElementB.getClass().getSimpleName()); } }
public class ConcreteVisitorTwo implements Visitor { @Override public void visitElementA(ConcreteElementA concreteElementA) { System.out.println(this.getClass().getSimpleName() + "访问" + concreteElementA.getClass().getSimpleName()); } @Override public void visitElementB(ConcreteElementB concreteElementB) { System.out.println(this.getClass().getSimpleName() + "访问" + concreteElementB.getClass().getSimpleName()); } }
public interface Element{ public void accept(Visitor visitor); }
public class ConcreteElementA implements Element{ @Override public void accept(Visitor visitor) { visitor.visitElementA(this); } }
public class ConcreteElementB implements Element{ @Override public void accept(Visitor visitor) { visitor.visitElementB(this); } }
public class Component { private List<Element> list = new ArrayList<>(); public void add(Element element) { list.add(element); } public void delete(Element element) { list.remove(element); } public void accept(Visitor visitor) { for (Element element : list) { element.accept(visitor); } } }
public class VisitorDemo{ public static void main(String[] args) { Component component = new Component(); component.add(new ConcreteElementA()); component.add(new ConcreteElementB()); ConcreteVisitorOne visitorOne = new ConcreteVisitorOne(); ConcreteVisitorTwo visitorTwo = new ConcreteVisitorTwo(); component.accept(visitorOne); component.accept(visitorTwo); } }
标签:visitor get 一个 string ide com nta static simple
原文地址:http://www.cnblogs.com/emoji1213/p/7679126.html