设计模式之访问(visitor)
程序员文章站
2022-05-04 14:09:52
...
public class VisitorDemo { public static void main(String[] args) { Collection c = new ArrayList(); c.add(new StringElement("string1")); c.add(new StringElement("string2")); c.add(new FloatElement(1.0f)); c.add(new FloatElement(2.0f)); Visitor v = new ConcreteVisitor(); v.visitCollection(c); } } interface Visitor{ void visitStringElement(StringElement stringElement); void visitFloatElement(FloatElement floatElement); void visitCollection(Collection collection); } class ConcreteVisitor implements Visitor{ public void visitCollection(Collection collection) { Iterator iter = collection.iterator(); while(iter.hasNext()){ Object obj = iter.next(); if(obj instanceof Visitable){ ((Visitable) obj).accept(this); } } } public void visitFloatElement(FloatElement floatElement) { System.out.println(floatElement.getValue()); } public void visitStringElement(StringElement stringElement) { System.out.println(stringElement.getValue()); } }//http://fengzl.iteye.com/blog/114758
上一篇: Vscode新建html文件
下一篇: C语言学习笔记丨带你五分钟了解指针!