A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 李江 中级黑马   /  2013-10-14 22:32  /  1718 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

转自:http://alaric.iteye.com/blog/1942517

访问者(Visitor)模式:封装一些作用于某种数据结构中的各元素的操作,它可以在不改变这个数据结构的前提下定义作用于这些元素的新的操作。访问者模式的结构图如下:


通过上图可以看到他有如下角色:

抽象访问者(Visitor)角色:定义接口,声明一个或多个访问操作。
具体访问者(ConcreteVisitor)角色:实现抽象访问者所声明的接口,也就是抽象访问者所声明的各个访问操作。
抽象元素(Visitable)角色:声明一个接受操作,接受一个访问者对象作为一个参数。
具体元素结点(ConcreteElement)角色:实现抽象结点所规定的接受操作。
数据结构对象(ObjectStructure)角色:可以遍历结构中的所有元素,提供一个接口让访问者对象都可以访问每一个元素。

模拟代码如下:
Java代码  

  • package visitor;  
  • /**
  • *  
  • *作者:alaric
  • *时间:2013-9-13下午11:31:28
  • *描述:抽象访问者
  • */  
  • public interface Visitor {  
  •   
  •     public void visit(ConcreteElementB able );  
  •     public void visit(ConcreteElementA able );  
  • }  

Java代码  

  • package visitor;  
  • /**
  • *  
  • *作者:alaric
  • *时间:2013-9-13下午11:31:46
  • *描述:抽象角色元素
  • */  
  • public interface Visitable {  
  •       
  •     public void accept(Visitor v);  
  •   
  • }  

Java代码  

  • package visitor;  
  • /**
  • *  
  • *作者:alaric
  • *时间:2013-9-13下午11:33:29
  • *描述:具体访问者A
  • */  
  • public class ConcreteVisitorA implements Visitor{  
  •   
  •     @Override  
  •     public void visit(ConcreteElementB able) {  
  •         able.operate();  
  •     }  
  •   
  •     @Override  
  •     public void visit(ConcreteElementA able) {  
  •         // TODO Auto-generated method stub  
  •         able.operate();  
  •     }  
  •       
  •   
  • }  

Java代码  

  • package visitor;  
  •   
  • /**
  • *  
  • *作者:alaric
  • *时间:2013-9-13下午11:32:55
  • *描述:具体访问者B
  • */  
  • public class ConcreteVisitorB implements Visitor{  
  •   
  •     @Override  
  •     public void visit(ConcreteElementB able) {  
  •         able.operate();  
  •     }  
  •   
  •     @Override  
  •     public void visit(ConcreteElementA able) {  
  •         // TODO Auto-generated method stub  
  •         able.operate();  
  •     }  
  •   
  •       
  •   
  • }  

Java代码  

  • package visitor;  
  • /**
  • *  
  • *作者:alaric
  • *时间:2013-9-13下午11:34:02
  • *描述:具体元素A
  • */  
  • public class ConcreteElementA implements Visitable {  
  •   
  •     @Override  
  •     public void accept(Visitor v) {  
  •         v.visit(this);  
  •     }  
  •   
  •     public void operate(){  
  •         System.out.println("ConcreteElementA ....");  
  •     }  
  • }  

Java代码  

  • package visitor;  
  • /**
  • *  
  • *作者:alaric
  • *时间:2013-9-13下午11:33:40
  • *描述:具体元素B
  • */  
  • public class ConcreteElementB implements Visitable {  
  •   
  •     @Override  
  •     public void accept(Visitor v) {  
  •         v.visit(this);  
  •     }  
  •   
  •     public void operate(){  
  •         System.out.println("ConcreteElementB ....");  
  •     }  
  • }  

Java代码  

  • package visitor;  
  •   
  • import java.util.ArrayList;  
  • import java.util.List;  
  • /**
  • *  
  • *作者:alaric
  • *时间:2013-9-13下午11:34:22
  • *描述:客户端
  • */  
  • public class Client {  
  •   
  •     /**
  •      * @param args
  •      */  
  •     public static void main(String[] args) {  
  •          
  •         Visitor v1 = new ConcreteVisitorA();  
  •         List<Visitable> list = new ArrayList<>();  
  •         list.add(new ConcreteElementA());  
  •         list.add(new ConcreteElementB());  
  •          
  •         for(Visitable able :list){  
  •             able.accept(v1);  
  •         }  
  •       
  •     }  
  •   
  • }  




5 个回复

倒序浏览

看了很多设计模式的书,讲访问者设计模式都要提到一个概念“双重分派”,所谓“分派”简单理解就是根据类的特性,特征进行选择,这些选择都是程序语言设计的特征,比如多态(重载,重写)等等,我个人不太注重概念,只要深入掌握面向对象的基础就很好理解了。


设计模式相对其他模式来说结构有点复杂,上面是访问者模式的模拟实现,为了利于学习找了个真实的例子。dom4j里面利用访问者模式来对xml文档进行逐个节点访问,所有文档的对象的父类接口都是Node,对于不同类型的文档对象又做了不同的抽象,所有可能访问的节点如Visitor类中所示,dom4j中定义的Visitor接口如下:


回复 使用道具 举报

Java代码  


    1. /*
    2. * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
    3. *
    4. * This software is open source.
    5. * See the bottom of this file for the licence.
    6. */  
    7.   
    8. package org.dom4j;  
    9.   
    10. /**
    11. * <p>
    12. * <code>Visitor</code> is used to implement the <code>Visitor</code>
    13. * pattern in DOM4J. An object of this interface can be passed to a
    14. * <code>Node</code> which will then call its typesafe methods. Please refer
    15. * to the <i>Gang of Four </i> book of Design Patterns for more details on the
    16. * <code>Visitor</code> pattern.
    17. * </p>
    18. *  
    19. * <p>
    20. * This <a href="http://www.patterndepot.com/put/8/JavaPatterns.htm">site </a>
    21. * has further discussion on design patterns and links to the GOF book. This <a
    22. * href="http://www.patterndepot.com/put/8/visitor.pdf">link </a> describes the
    23. * Visitor pattern in detail.
    24. * </p>
    25. *  
    26. * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
    27. * @version $Revision: 1.8 $
    28. */  
    29. public interface Visitor {  
    30.     /**
    31.      * <p>
    32.      * Visits the given <code>Document</code>
    33.      * </p>
    34.      *  
    35.      * @param document
    36.      *            is the <code>Document</code> node to visit.
    37.      */  
    38.     void visit(Document document);  
    39.   
    40.     /**
    41.      * <p>
    42.      * Visits the given <code>DocumentType</code>
    43.      * </p>
    44.      *  
    45.      * @param documentType
    46.      *            is the <code>DocumentType</code> node to visit.
    47.      */  
    48.     void visit(DocumentType documentType);  
    49.   
    50.     /**
    51.      * <p>
    52.      * Visits the given <code>Element</code>
    53.      * </p>
    54.      *  
    55.      * @param node
    56.      *            is the <code>Element</code> node to visit.
    57.      */  
    58.     void visit(Element node);  
    59.   
    60.     /**
    61.      * <p>
    62.      * Visits the given <code>Attribute</code>
    63.      * </p>
    64.      *  
    65.      * @param node
    66.      *            is the <code>Attribute</code> node to visit.
    67.      */  
    68.     void visit(Attribute node);  
    69.   
    70.     /**
    71.      * <p>
    72.      * Visits the given <code>CDATA</code>
    73.      * </p>
    74.      *  
    75.      * @param node
    76.      *            is the <code>CDATA</code> node to visit.
    77.      */  
    78.     void visit(CDATA node);  
    79.   
    80.     /**
    81.      * <p>
    82.      * Visits the given <code>Comment</code>
    83.      * </p>
    84.      *  
    85.      * @param node
    86.      *            is the <code>Comment</code> node to visit.
    87.      */  
    88.     void visit(Comment node);  
    89.   
    90.     /**
    91.      * <p>
    92.      * Visits the given <code>Entity</code>
    93.      * </p>
    94.      *  
    95.      * @param node
    96.      *            is the <code>Entity</code> node to visit.
    97.      */  
    98.     void visit(Entity node);  
    99.   
    100.     /**
    101.      * <p>
    102.      * Visits the given <code>Namespace</code>
    103.      * </p>
    104.      *  
    105.      * @param namespace
    106.      *            is the <code>Namespace</code> node to visit.
    107.      */  
    108.     void visit(Namespace namespace);  
    109.   
    110.     /**
    111.      * <p>
    112.      * Visits the given <code>ProcessingInstruction</code>
    113.      * </p>
    114.      *  
    115.      * @param node
    116.      *            is the <code>ProcessingInstruction</code> node to visit.
    117.      */  
    118.     void visit(ProcessingInstruction node);  
    119.   
    120.     /**
    121.      * <p>
    122.      * Visits the given <code>Text</code>
    123.      * </p>
    124.      *  
    125.      * @param node
    126.      *            is the <code>Text</code> node to visit.
    127.      */  
    128.     void visit(Text node);  
    129. }  
    130.   
    131. /*
    132. * Redistribution and use of this software and associated documentation
    133. * ("Software"), with or without modification, are permitted provided that the
    134. * following conditions are met:
    135. *  
    136. * 1. Redistributions of source code must retain copyright statements and
    137. * notices. Redistributions must also contain a copy of this document.
    138. *  
    139. * 2. Redistributions in binary form must reproduce the above copyright notice,
    140. * this list of conditions and the following disclaimer in the documentation
    141. * and/or other materials provided with the distribution.
    142. *  
    143. * 3. The name "DOM4J" must not be used to endorse or promote products derived
    144. * from this Software without prior written permission of MetaStuff, Ltd. For
    145. * written permission, please contact dom4j-info@metastuff.com.
    146. *  
    147. * 4. Products derived from this Software may not be called "DOM4J" nor may
    148. * "DOM4J" appear in their names without prior written permission of MetaStuff,
    149. * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
    150. *  
    151. * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
    152. *  
    153. * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
    154. * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    155. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    156. * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
    157. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    158. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    159. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    160. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    161. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    162. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    163. * POSSIBILITY OF SUCH DAMAGE.
    164. *  
    165. * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
    166. */  
    复制代码

dom4j里面有个缺省的访问者(Visitor)的实现VisitorSupport,我们解析一个文档只需继承这个类,然后重写visit方法即可。一个简单的类图表示dom4j是怎么利用visitor设计模式的,如下图:




回复 使用道具 举报
上图中Node的继承接口和实现类 还有很多这里就只标示了CharacterData及其他的子类。我只需要写XXX_Visitor就可以了。接下来我们写个例子看看:
我们要解析的XML如下:Java代码  

  • <?xml version="1.0" encoding="UTF-8"?>  
  • <table name="test">  
  •   <rows>  
  •       <row>  
  •         <id>1</id>  
  •         <test>Test</test>  
  •       </row>  
  •       <row>  
  •         <id>2</id>  
  •         <test>Test2</test>  
  •       </row>   
  • </rows  
  • </table>  

我们写个客户端测试,为了简单,把Visitor作为内部类,直接就一个类完成,代码如下:  Java代码  

  • package com.alaric.dom4j;  
  •   
  • import java.io.File;  
  •   
  • import org.dom4j.Attribute;  
  • import org.dom4j.Document;  
  • import org.dom4j.DocumentException;  
  • import org.dom4j.Element;  
  • import org.dom4j.VisitorSupport;  
  • import org.dom4j.io.SAXReader;  
  •   
  • public class Dom4jTest {  
  •   
  •   
  •     public class MyVisitor extends VisitorSupport {  
  •   
  •         public void visit(Attribute node){  
  •           System.out.println("属性 : "+node.getName()+" = "+node.getValue());  
  •         }  
  •   
  •         public void visit(Element node){  
  •           if(node.isTextOnly()){  
  •             System.out.println("节点: "+node.getName()+" = "+node.getText());  
  •           }else{  
  •             System.out.println("节点:"+node.getName());  
  •           }  
  •         }  
  •     }  
  •   
  •   
  •     public static void main(String[] args) throws Exception {  
  •   
  •         SAXReader saxReader=new SAXReader();  
  •         File file=new File("d:\\test.xml");  
  •         try{  
  •           Document doc=saxReader.read(file);  
  •           doc.accept(new Dom4jTest(). new MyVisitor());  
  •         }catch(DocumentException de){  
  •           de.printStackTrace();  
  •         }  
  •   
  •     }  
  •   
  • }  


运行结果:
节点:table
属性 : name = test
节点:rows
节点:row
节点: id = 1
节点: test = Test
节点:row
节点: id = 2
节点: test = Test2

可以看出把xml节点顺序的访问了一边。每个人可以根据不同的xml来实现自己的Visitor,不论怎么写都可以遍历出你所有的节点,这就是visitor的厉害之处。访问者模式也不是万能的,他的缺点是当数据结构变化时,他的visitor接口及其实现都要改变。所以访问者模式不能使用在经常变化的数据接口上。在Gof的设计模式中,有以下情形可以考虑使用设计模式:

1、一个对象结构包含很多类对象,它们有不同的接口,而你想对这些对象实施一些依赖于其具体类的操作。
2、需要对一个对象结构中的对象进行很多不同的并且不相关的操作,而你想避免让这些操作“污染”这些对象的类。Visitor使得你可以将相关的操作集中起来定义在一个类中。
3、当该对象结构被很多应用共享时,用Visitor模式让每个应用仅包含需要用到的操作。
4、 定义对象结构的类很少改变,但经常需要在此结构上定义新的操作。改变对象结构类需要重定义对所有访问者的接口,这可能需要很大的代价。如果对象结构类经常改变,那么可能还是在这些类中定义这些操作较好。
这些个人看来都是建议,项目中还要具体问题具体分析了。




回复 使用道具 举报
FFF 金牌黑马 2013-10-14 22:54:45
报纸
谢谢分享,但能不能把你的设计模式的学习打包一个,给我们这些小的。像下载某个苍老师一样下载到我们的硬盘呢?{:soso_e113:}
回复 使用道具 举报
FFF 发表于 2013-10-14 22:54
谢谢分享,但能不能把你的设计模式的学习打包一个,给我们这些小的。像下载某个苍老师一样下载到我们的硬盘 ...

哈哈 好邪恶
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马