首页 > 代码库 > 设计模式之访问者模式

设计模式之访问者模式

定义:表示一介作用于某个对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。

结构图:


示例代码:

public interface Vistor {

	public abstract void vistorConcreteElementA(ConcreteElementA concreteElementA);
	public abstract void vistorConcreteElementB(ConcreteElementB concreteElementB);
}

public class ConcreteVisitor1 implements Vistor {

	@Override
	public void vistorConcreteElementA(ConcreteElementA concreteElementA) {
		// TODO Auto-generated method stub
		System.out.println(concreteElementA.getClass().getName() + " " + this.getClass().getName());
	}

	@Override
	public void vistorConcreteElementB(ConcreteElementB concreteElementB) {
		// TODO Auto-generated method stub
		System.out.println(concreteElementB.getClass().getName() + " " + this.getClass().getName());
	}

}

public class ConcreteVistor2 implements Vistor {

	@Override
	public void vistorConcreteElementA(ConcreteElementA concreteElementA) {
		// TODO Auto-generated method stub
		System.out.println(concreteElementA.getClass().getName() + " " + this.getClass().getName());
	}

	@Override
	public void vistorConcreteElementB(ConcreteElementB concreteElementB) {
		// TODO Auto-generated method stub
		System.out.println(concreteElementB.getClass().getName() + " " + this.getClass().getName());
	}

}
public abstract class Element {

	public abstract void accept(Vistor vistor);
}
public class ConcreteElementA extends Element {

	@Override
	public void accept(Vistor vistor) {
		// TODO Auto-generated method stub
		vistor.vistorConcreteElementA(this);
	}

	public void OperationA() {
		
	}
}
public class ConcreteElementB extends Element{

	@Override
	public void accept(Vistor vistor) {
		// TODO Auto-generated method stub
		vistor.vistorConcreteElementB(this);
	}

	public void OperationB() {
		
	}
}
public class ObjectStructure {

	private List<Element> elements = new ArrayList<Element>();
	
	public void attach(Element element) {
		
		elements.add(element);
	}
	
	public void detach(Element element) {
		
		elements.remove(element);
	}
	
	public void accept(Vistor vistor) {
		for (Element e: elements) {
			e.accept(vistor);
		}
	}
}
客户端代码如下:
public class Client {

	public static void main(String[] args) {
		
		ObjectStructure o = new ObjectStructure();
		o.attach(new ConcreteElementA());
		o.attach(new ConcreteElementB());
		ConcreteVisitor1 v1 = new ConcreteVisitor1();
		ConcreteVistor2  v2 = new ConcreteVistor2();
		o.accept(v1);
		o.accept(v2);
	}
}

输出结果:

strategy.vistor.ConcreteElementA strategy.vistor.ConcreteVisitor1

strategy.vistor.ConcreteElementB strategy.vistor.ConcreteVisitor1

strategy.vistor.ConcreteElementA strategy.vistor.ConcreteVistor2

strategy.vistor.ConcreteElementBstrategy.vistor.ConcreteVistor2



设计模式之访问者模式