标签:
访问者模式(Vistor),表示一个作用于某对象结构中的各个元素的操作,它使你可以在不改变各个元素的类的前提下定义作用于这些元素的新操作。
|
|
package com.zcr.vistor; public abstract class Element { public abstract void Accept(Vistor vistor); }
package com.zcr.vistor; public class ConcreteElementA extends Element { //充分利用双分派技术,实现处理与数据结构的分离 @Override public void Accept(Vistor vistor) { vistor.VistConcreteElementA(this); } public void OperationA() { } }
package com.zcr.vistor; public class ConcreteElementB extends Element { @Override public void Accept(Vistor vistor) { vistor.VistConcreteElementB(this); } public void OperationB() { } }
package com.zcr.vistor; public abstract class Vistor { public abstract void VistConcreteElementA(ConcreteElementA concreteElementA); public abstract void VistConcreteElementB(ConcreteElementB concreteElementB); }
package com.zcr.vistor; public class ConcreteVistor1 extends Vistor { @Override public void VistConcreteElementA(ConcreteElementA concreteElementA) { System.out.println(concreteElementA.getClass().getName()+"被"+this.getClass().getName()+"访问"); } @Override public void VistConcreteElementB(ConcreteElementB concreteElementB) { System.out.println(concreteElementB.getClass().getName()+"被"+this.getClass().getName()+"访问"); } }
package com.zcr.vistor; public class ConcreteVistor2 extends Vistor { @Override public void VistConcreteElementA(ConcreteElementA concreteElementA) { System.out.println(concreteElementA.getClass().getName()+"被"+this.getClass().getName()+"访问"); } @Override public void VistConcreteElementB(ConcreteElementB concreteElementB) { System.out.println(concreteElementB.getClass().getName()+"被"+this.getClass().getName()+"访问"); } }
package com.zcr.vistor; import java.util.ArrayList; import java.util.List; 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); } } }
package com.zcr.vistor; public class VistorTest { public static void main(String[] args) { ObjectStructure o = new ObjectStructure(); o.Attach(new ConcreteElementA()); o.Attach(new ConcreteElementB()); ConcreteVistor1 v1= new ConcreteVistor1(); ConcreteVistor2 v2= new ConcreteVistor2(); o.Accept(v1); o.Accept(v2); } }
标签:
原文地址:http://www.cnblogs.com/0201zcr/p/4613412.html