设计模式之Visitor(访问者模式)
Visitor(访问者模式)
访问者
package com.dzeay.pattern.visitor; public interface Visitor { void visitorConcreteElementA(ConcreteElementA concreteElementA); void visitorConcreteElementB(ConcreteElementB concreteElementB); }
具体访问者
package com.dzeay.pattern.visitor; public class ConcreteVisitor implements Visitor { @Override public void visitorConcreteElementA(ConcreteElementA concreteElementA) { System.out.println("ConcreteVisitor.visitorConcreteElementA"); } @Override public void visitorConcreteElementB(ConcreteElementB concreteElementB) { System.out.println("ConcreteVisitor.visitorConcreteElementB"); } }
元素,定义一个accept操作,该操作以一个访问者为参数
package com.dzeay.pattern.visitor; public interface Element { void accept(Visitor visitor); }
具体元素,实现accept操作
package com.dzeay.pattern.visitor; public class ConcreteElementA implements Element { @Override public void accept(Visitor visitor) { visitor.visitorConcreteElementA(this); } }
package com.dzeay.pattern.visitor; public class ConcreteElementB implements Element { @Override public void accept(Visitor visitor) { visitor.visitorConcreteElementB(this); } }
Visitor--测试类
package com.dzeay.pattern.visitor; /** * <pre> * Visitor(访问者模式)详解: * 表示作用于某对象结构中的各元素的操作.它可以使得你在不改变和元素的类的前提下定义作用于这些元素的新操作. * </pre> * * @author <a href="mailto:[email protected]">dzeay.com</a> * @since 2011-02-26 * @version 1.0 */ public class TestClass { /** * @param args */ public static void main(String[] args) { Visitor visitor = new ConcreteVisitor(); Element elementA = new ConcreteElementA(); Element elementB = new ConcreteElementB(); elementA.accept(visitor); elementB.accept(visitor); } }设计模式之Visitor(访问者模式)
相关推荐
TingBen 2020-09-16
Kakoola 2020-01-12
Clevebaby 2012-04-23
New丶Elements 2019-06-27
AHRL 2011-02-17
守望丶 2011-01-19
Backwardelements 2010-12-18
guojing 2010-01-27
lujingjing 2016-05-03
fancyler 2018-02-05
thousfeet 2015-07-23
shonmark 2016-11-18
githubphpnobug 2019-04-17
PHP100 2019-03-28
vczh的日常 2018-04-21
前端外刊评论 2018-03-05
MATLAB 2017-11-28