欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

设计模式之访问(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