Design Patterns twenty-one: visitor pattern (Visitor)

In real life, some collection of objects exist in a number of different elements, and each element there are a variety of different visitors and handling. For example, there are several attractions in the park, there are more tourists, tourists of different evaluation of the same attractions may be different; the hospital doctor's prescription drug contains a variety of elements, see its designated price and pharmacy staff members its approach is different, members were designated price mark-name drugs based on the number of prescriptions and above, the pharmacy staff to fill a prescription based on the contents of the prescription.

There are many such examples, for example, the characters in the movie or TV show, the evaluation of the different audiences they are different; customers on the "shopping cart" of goods when shopping there, customers primarily concerned with selected products value for money, and the cashier concerned about is the price and quantity of goods.

These data elements are processed in a relatively stable manner and access a wide variety of data structures , if treated with "visitor mode" more convenient. Visitor pattern processing method can separate out from the data structure, and can add a new processing method as needed, and do not modify the original program code and data structures, which improves the scalability and flexibility of the program.

The definition and characteristics of the model

The new separating operation of each operation element is applied to a certain data structure encapsulates them into separate categories, so that it can be added without changing the structure of the data under the premise of acting on these elements: definition of visitors (Visitor) mode provide a variety of ways to access the data structure of each element. It will be separated with the operation of the data structure data, the behavior is the most complex model-based mode.

Visitors (Visitor) model is an object behavioral pattern, its main advantages are as follows.

  1. Good scalability. It is possible without modifying the structure element objects, add new features to the object structure elements.
  2. Good reusability. The whole object can be defined by structural features common visitor, thereby increasing the degree of multiplexing system.
  3. Good flexibility. Visitors mode data structure applied to the operation of the decoupling structure, so that the operation can be set relatively freely without affecting the evolution of the system data structures.
  4. In line with the principle of single responsibility. The visitor pattern related behaviors packaged together, constitute a visitor, so that every visitor functions are relatively simple.


The main disadvantage of visitors (Visitor) mode are as follows.

  1. Add new elements class is difficult. In visitor mode, each new element type, have a corresponding increase in the specific operation of a particular visitor each class, which is contrary to the "on-off principle."
  2. Violate encapsulation. Visitor pattern specific elements of the published details of a visitor, this break encapsulation object.
  3. Violates the Dependency Inversion Principle. Visitor pattern dependent on a specific category, but not rely on abstract classes.

Architecture and Implementation Model

Key visitor (Visitor) mode is how to achieve the operating element acting on the separate package into separate classes, the basic structure and method is as follows.

1. Structure Model

Visitor pattern consists of the following major role.

  1. Abstract visitor (Visitor) Roles: define an interface to access a specific element, for each class corresponding to a particular access operation element Visit (), the type of operation parameter identifies the particular element to be accessed.
  2. Specific visitors (ConcreteVisitor) Role: The abstract role of visitors declared in each access operation, to determine what to do when a visitor accesses elements.
  3. Abstract elements (Element) role: a declaration containing interface accepts operating accept (), and accepted the visitor object as a parameter accept () method.
  4. DETAILED element (ConcreteElement) Role: The abstract character element provided accept () operation, which is usually a method thereof visitor.visit (this), it is specifically related elements may also contain service logic operation itself.
  5. Object structure (Object Structure) Role: role is a container element containing provide all the elements for visitors to traverse the objects in the container method is usually implemented by List, Set, Map and other polymerization class.


The structure shown in Figure 1.
 

                        FIG visitor structure (Visitor) mode
 

2. Mode of realization

Visitor pattern implementation code as follows:

package visitor;
import java.util.*;
public class VisitorPattern
{
    public static void main(String[] args)
    {
        ObjectStructure os=new ObjectStructure();
        os.add(new ConcreteElementA());
        os.add(new ConcreteElementB());
        Visitor visitor=new ConcreteVisitorA();
        os.accept(visitor);
        System.out.println("------------------------");
        visitor=new ConcreteVisitorB();
        os.accept(visitor);
    }
}
//抽象访问者
interface Visitor
{
    void visit(ConcreteElementA element);
    void visit(ConcreteElementB element);
}
//具体访问者A类
class ConcreteVisitorA implements Visitor
{
    public void visit(ConcreteElementA element)
    {
        System.out.println("具体访问者A访问-->"+element.operationA());
    }
    public void visit(ConcreteElementB element)
    {
        System.out.println("具体访问者A访问-->"+element.operationB());
    }
}
//具体访问者B类
class ConcreteVisitorB implements Visitor
{
    public void visit(ConcreteElementA element)
    {
        System.out.println("具体访问者B访问-->"+element.operationA());
    }
    public void visit(ConcreteElementB element)
    {
        System.out.println("具体访问者B访问-->"+element.operationB());
    }
}
//抽象元素类
interface Element
{
    void accept(Visitor visitor);
}
//具体元素A类
class ConcreteElementA implements Element
{
    public void accept(Visitor visitor)
    {
        visitor.visit(this);
    }
    public String operationA()
    {
        return "具体元素A的操作。";
    }
}
//具体元素B类
class ConcreteElementB implements Element
{
    public void accept(Visitor visitor)
    {
        visitor.visit(this);
    }
    public String operationB()
    {
        return "具体元素B的操作。";
    }
}
//对象结构角色
class ObjectStructure
{   
    private List<Element> list=new ArrayList<Element>();   
    public void accept(Visitor visitor)
    {
        Iterator<Element> i=list.iterator();
        while(i.hasNext())
        {
            ((Element) i.next()).accept(visitor);
        }      
    }
    public void add(Element element)
    {
        list.add(element);
    }
    public void remove(Element element)
    {
        list.remove(element);
    }
}

Operating results of the program are as follows: 

具体访问者A访问-->具体元素A的操作。
具体访问者A访问-->具体元素B的操作。
------------------------
具体访问者B访问-->具体元素A的操作。
具体访问者B访问-->具体元素B的操作。

Mode of application examples

[Example 1] using the 'Visitor (Visitor) mode "Analog Arts and Minting Company's functional.

Analysis: Arts using "copper" statue may be devised, using a "paper" can draw a picture; Mint use "copper" coins can be printed, using a "paper" can print the bill. Of "copper" and "paper" of these two elements, two different companies processing method, so the example to achieve more suitable for use visitor pattern.

First, the definition of a company (Company) interface, which is an abstract visitors, provides two methods for creating the works in the paper (Paper) or copper (Cuprum) of these two elements; redefinition Arts (ArtCompany) class and coinage company (Mint) class, which are specific visitor, implements the method of the parent interface; then, define a material (material) interface, which is an abstract element, provided accept (company visitor) method for receiving visitors (company) Object access; redefinition paper (paper) class and copper (Cuprum) class, which are a particular element type, implements a method on the parent interface; Finally, define a material of the collector (SetMaterial) class, which is the object of roles, has saved all container element List, and to provide for visitors to traverse the object accept all elements of the container (Company visitor) method; customer category designed to form a program that provides material set (SetMaterial) objects for visitors (Company) object access, ItemListener implements the interface, event handling user requests. Figure 2 is a structural view.
 

                 Arts and Minting Company structure chart


Code is as follows:

package visitor;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class VisitorProducer
{
    public static void main(String[] args)
    {
        new MaterialWin();       
    }
}
//窗体类
class MaterialWin extends JFrame implements ItemListener
{
    private static final long serialVersionUID=1L;   
    JPanel CenterJP;
    SetMaterial os;    //材料集对象
    Company visitor1,visitor2;    //访问者对象
    String[] select;
    MaterialWin()
    {
        super("利用访问者模式设计艺术公司和造币公司");
        JRadioButton Art;
        JRadioButton mint;           
        os=new SetMaterial();     
        os.add(new Cuprum());
        os.add(new Paper());
        visitor1=new ArtCompany();//艺术公司
        visitor2=new Mint(); //造币公司      
        this.setBounds(10,10,750,350);            
        this.setResizable(false);       
        CenterJP=new JPanel();       
        this.add("Center",CenterJP);      
        JPanel SouthJP=new JPanel();
        JLabel yl=new JLabel("原材料有:铜和纸,请选择生产公司:");
        Art=new JRadioButton("艺术公司",true);
        mint=new JRadioButton("造币公司");
        Art.addItemListener(this);
        mint.addItemListener(this);       
        ButtonGroup group=new ButtonGroup();
        group.add(Art);
        group.add(mint);
        SouthJP.add(yl);
        SouthJP.add(Art);
        SouthJP.add(mint);
        this.add("South",SouthJP);       
        select=(os.accept(visitor1)).split(" ");    //获取产品名
        showPicture(select[0],select[1]);    //显示产品
    }
    //显示图片
    void showPicture(String Cuprum,String paper)
    {
        CenterJP.removeAll();    //清除面板内容
        CenterJP.repaint();    //刷新屏幕
        String FileName1="src/visitor/Picture/"+Cuprum+".jpg";
        String FileName2="src/visitor/Picture/"+paper+".jpg";
        JLabel lb=new JLabel(new ImageIcon(FileName1),JLabel.CENTER);
        JLabel rb=new JLabel(new ImageIcon(FileName2),JLabel.CENTER);
        CenterJP.add(lb);
        CenterJP.add(rb);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);            
    }
    @Override
    public void itemStateChanged(ItemEvent arg0)
    {
        JRadioButton jc=(JRadioButton) arg0.getSource();
        if (jc.isSelected())
        {
            if (jc.getText()=="造币公司")
            {
                select=(os.accept(visitor2)).split(" ");
            }
            else
            {            
                select=(os.accept(visitor1)).split(" ");
            }
            showPicture(select[0],select[1]);    //显示选择的产品
        }    
    }
}
//抽象访问者:公司
interface Company
{
    String create(Paper element);
    String create(Cuprum element);
}
//具体访问者:艺术公司
class ArtCompany implements Company
{
    public String create(Paper element)
    {
        return "讲学图";
    }
    public String create(Cuprum element)
    {
        return "朱熹铜像";
    }
}
//具体访问者:造币公司
class Mint implements Company
{
    public String create(Paper element)
    {
        return "纸币";
    }
    public String create(Cuprum element)
    {
        return "铜币";
    }
}
//抽象元素:材料
interface Material
{
    String accept(Company visitor);
}
//具体元素:纸
class Paper implements Material
{
    public String accept(Company visitor)
    {
        return(visitor.create(this));
    }
}
//具体元素:铜
class Cuprum implements Material
{
    public String accept(Company visitor)
    {
        return(visitor.create(this));
    }
}
//对象结构角色:材料集
class SetMaterial
{   
    private List<Material> list=new ArrayList<Material>();   
    public String accept(Company visitor)
    {
        Iterator<Material> i=list.iterator();
        String tmp="";
        while(i.hasNext())
        {
            tmp+=((Material) i.next()).accept(visitor)+" ";
        }
        return tmp; //返回某公司的作品集     
    }
    public void add(Material element)
    {
        list.add(element);
    }
    public void remove(Material element)
    {
        list.remove(element);
    }
}

Result of the program shown in Figure 3.
 

      Art-designed products
(A) Art-designed products

 

         Mint produced the money

 

Application of scene modes

Generally can be considered in the case of visitors (Visitor) mode.

  1. Object structure is relatively stable, but frequently changing operation algorithm program.
  2. Object structure of the object needs to provide a variety of different, unrelated operations, but also to avoid these changes affect the operation of the object structure.
  3. Object structure contains many types of objects, some of the desirable embodiments of these objects depends on its particular type of operation.

Extended mode

Visitors (Visitor) model is frequently used one kind of design pattern , it is often associated with the use of two design patterns.

(1) and " iterative mode " in combination. Because the visitor mode "object structure" is a container element contains the character, when visitors traverse all elements of the container, often use iterators. The object structure [Example 1] using the List is implemented, it gets through the iterator object Itemtor List () method. If the object class structure of the polymerization does not provide iterators, it may be a custom iterative mode.

(2) the visitor (Visitor) mode with " combined mode " in combination. Since the visitor (Visitor) mode "target element" may be a leaf object or a container object, if the object is a container object containing the element, it is necessary to use the combination mode , the structure shown in Figure 4.
 

                 FIG visitor pattern configuration comprises a combination of patterns

 

 

 

 

 

Published 136 original articles · won praise 6 · views 1538

Guess you like

Origin blog.csdn.net/weixin_42073629/article/details/104437896