Design Patterns Twenty: Iterator (Iterator)

In real life, as well as programming, often visit the various elements of a polymeric object, such as " data structure linked list traversal" in the common practice is to create a linked list traversal and are placed in the same class, but this way is not conducive to the extension, if you want to replace traversal methods must modify the source code, which is contrary to the "principle of opening and closing."

Since the package is not desirable in the polymerization traversal methods class, then traverse the method does not provide a polymerization class, traversal methods implemented by the user's own work? The answer is equally undesirable, because there will be two shortcomings of this approach:

  1. Class exposes the internal representation of the polymerization, so that data is insecure;
  2. Increasing the burden on customers.


"Iterative mode" can overcome the above drawbacks, it is inserted between a client access iterator class type polymerization, which separates the aggregate object and its traversal behavior, the customer also hides its internal details, and satisfies a "single the principle of responsibility "and" the principle of opening and closing, "such as  Java  in the Collection, List, Set, Map and so contain the iterator.

The definition and characteristics of the model

Iterator is defined (the Iterator) mode: an object to provide a series of sequential access data object polymerization, the polymerization without exposing the internal representation of the object. Iterator is an object behavioral pattern, its main advantages are as follows.

  1. Accessing a content object polymerization without exposing its internal representation.
  2. Handed over the task to complete traversal iterator, which simplifies the aggregation class.
  3. It supports different ways to traverse a polymerization, even customize iterator subclass to support the new traversal.
  4. Add a new class of polymeric iterator class and easy, without modifying the original code.
  5. Good encapsulation provides a unified interface to traverse different polymeric structure.


Its main disadvantages are: the number of classes increases, which increases the complexity of the system to some extent.

Architecture and Implementation Model

Iterative mode is isolated by traversing the object out of the polymerization behavior, abstracted into iterator class to achieve its object in the case of an internal structure of the aggregate object is not exposed, so that access to the interior transparent external code data aggregation. Now we have to analyze the basic structure and implementation.

1. Structure Model

Iterator pattern mainly includes the following roles.

  1. Abstract polymerization (Aggregate) roles: the definition of storage, add, delete, and create interfaces aggregate objects iterator object.
  2. Specific polymerization (ConcreteAggregate) Role: implement the abstract class polymerization, it returns an iterator specific examples.
  3. Abstract iterator (the Iterator) Role: defining access interface elements and traverse the polymerization, generally comprising hasNext (), first (), next () method and the like.
  4. DETAILED iterator (Concretelterator) Role: Abstract iterator interface implementation defined, complete traversal of the aggregate object, recording the current position of the traverse.


The structure shown in Figure 1.
 

                                  Mode of the structure of FIG iterator
 

2. Mode of realization

Iterator pattern codes are as follows:

package iterator;
import java.util.*;
public class IteratorPattern
{
    public static void main(String[] args)
    {
        Aggregate ag=new ConcreteAggregate(); 
        ag.add("中山大学"); 
        ag.add("华南理工"); 
        ag.add("韶关学院");
        System.out.print("聚合的内容有:");
        Iterator it=ag.getIterator(); 
        while(it.hasNext())
        { 
            Object ob=it.next(); 
            System.out.print(ob.toString()+"\t"); 
        }
        Object ob=it.first();
        System.out.println("\nFirst:"+ob.toString());
    }
}
//抽象聚合
interface Aggregate
{ 
    public void add(Object obj); 
    public void remove(Object obj); 
    public Iterator getIterator(); 
}
//具体聚合
class ConcreteAggregate implements Aggregate
{ 
    private List<Object> list=new ArrayList<Object>(); 
    public void add(Object obj)
    { 
        list.add(obj); 
    }
    public void remove(Object obj)
    { 
        list.remove(obj); 
    }
    public Iterator getIterator()
    { 
        return(new ConcreteIterator(list)); 
    }     
}
//抽象迭代器
interface Iterator
{
    Object first();
    Object next();
    boolean hasNext();
}
//具体迭代器
class ConcreteIterator implements Iterator
{ 
    private List<Object> list=null; 
    private int index=-1; 
    public ConcreteIterator(List<Object> list)
    { 
        this.list=list; 
    } 
    public boolean hasNext()
    { 
        if(index<list.size()-1)
        { 
            return true;
        }
        else
        {
            return false;
        }
    }
    public Object first()
    {
        index=0;
        Object obj=list.get(index);;
        return obj;
    }
    public Object next()
    { 
        Object obj=null; 
        if(this.hasNext())
        { 
            obj=list.get(++index); 
        } 
        return obj; 
    }   
}

Program results are as follows: 

聚合的内容有:中山大学    华南理工    韶关学院   
First:中山大学

Mode of application examples

Iterator pattern is written in a browser Wuyuan scenic tourist map program [Example 1].

Analysis: Wuyuan many monuments, to design a view attractions pictures and profiles of the program, with the "iterator pattern" design more appropriate.

First, design a Wuyuan attractions (WyViewSpot) class to hold the names and brief introduction of each picture; then design a set Attractions (ViewSpotSet) interface, which is an abstract class aggregation, providing additions and deletions Wuyuan attractions methods, and access iterator Methods.

Then, define a Wuyuan interest set (WyViewSpotSet) class, which is a concrete aggregate class, with ArrayList to save all the information on attractions and implement the abstract method in a parent class; redefined Wuyuan landscape abstract iterator (ViewSpotltemtor) interface, comprising the view method attractions information.

Finally, the definition of Wuyuan landscape specific iterator (WyViewSpotlterator) class, which implements the abstract parent class; client program designed window procedure, which data (ViewSpotSet) initializes Wuyuan attractions set, and implements the ActionListener interface, by Wuyuan attractions iterator (ViewSpotlterator) to view information Wuyuan attractions (WyViewSpot) of. Figure 2 is a structural view.
 

                            Structure Figure Wuyuan scenic tourist map browsing program


Code is as follows:

package iterator;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class PictureIterator{
    public static void main(String[] args)
    {
        new PictureFrame();
    }
}
//相框类
class PictureFrame extends JFrame implements ActionListener
{
    private static final long serialVersionUID=1L;
    ViewSpotSet ag; //婺源景点集接口
    ViewSpotIterator it; //婺源景点迭代器接口
    WyViewSpot ob;    //婺源景点类
    PictureFrame()
    {
        super("中国最美乡村“婺源”的部分风景图");
        this.setResizable(false);
        ag=new WyViewSpotSet(); 
        ag.add(new WyViewSpot("江湾","江湾景区是婺源的一个国家5A级旅游景区,景区内有萧江宗祠、永思街、滕家老屋、婺源人家、乡贤园、百工坊等一大批古建筑,精美绝伦,做工精细。")); 
        ag.add(new WyViewSpot("李坑","李坑村是一个以李姓聚居为主的古村落,是国家4A级旅游景区,其建筑风格独特,是著名的徽派建筑,给人一种安静、祥和的感觉。")); 
        ag.add(new WyViewSpot("思溪延村","思溪延村位于婺源县思口镇境内,始建于南宋庆元五年(1199年),当时建村者俞氏以(鱼)思清溪水而名。"));
        ag.add(new WyViewSpot("晓起村","晓起有“中国茶文化第一村”与“国家级生态示范村”之美誉,村屋多为清代建筑,风格各具特色,村中小巷均铺青石,曲曲折折,回环如棋局。")); 
        ag.add(new WyViewSpot("菊径村","菊径村形状为山环水绕型,小河成大半圆型,绕村庄将近一周,四周为高山环绕,符合中国的八卦“后山前水”设计,当地人称“脸盆村”。")); 
        ag.add(new WyViewSpot("篁岭","篁岭是著名的“晒秋”文化起源地,也是一座距今近六百历史的徽州古村;篁岭属典型山居村落,民居围绕水口呈扇形梯状错落排布。"));
        ag.add(new WyViewSpot("彩虹桥","彩虹桥是婺源颇有特色的带顶的桥——廊桥,其不仅造型优美,而且它可在雨天里供行人歇脚,其名取自唐诗“两水夹明镜,双桥落彩虹”。")); 
        ag.add(new WyViewSpot("卧龙谷","卧龙谷是国家4A级旅游区,这里飞泉瀑流泄银吐玉、彩池幽潭碧绿清新、山峰岩石挺拔奇巧,活脱脱一幅天然泼墨山水画。"));
        it = ag.getIterator(); //获取婺源景点迭代器 
        ob = it.first(); 
        this.showPicture(ob.getName(),ob.getIntroduce());
    }
    //显示图片
    void showPicture(String Name,String Introduce)
    {       
        Container cp=this.getContentPane();       
        JPanel picturePanel=new JPanel();
        JPanel controlPanel=new JPanel();       
        String FileName="src/iterator/Picture/"+Name+".jpg";
        JLabel lb=new JLabel(Name,new ImageIcon(FileName),JLabel.CENTER);   
        JTextArea ta=new JTextArea(Introduce);       
        lb.setHorizontalTextPosition(JLabel.CENTER);
        lb.setVerticalTextPosition(JLabel.TOP);
        lb.setFont(new Font("宋体",Font.BOLD,20));
        ta.setLineWrap(true);       
        ta.setEditable(false);
        //ta.setBackground(Color.orange);
        picturePanel.setLayout(new BorderLayout(5,5));
        picturePanel.add("Center",lb);       
        picturePanel.add("South",ta);       
        JButton first, last, next, previous;
        first=new JButton("第一张");
        next=new JButton("下一张");
        previous=new JButton("上一张");
        last=new JButton("最末张");
        first.addActionListener(this);
        next.addActionListener(this);
        previous.addActionListener(this);
        last.addActionListener(this);        
        controlPanel.add(first);
        controlPanel.add(next);
        controlPanel.add(previous);
        controlPanel.add(last);       
        cp.add("Center",picturePanel);
        cp.add("South",controlPanel);
        this.setSize(630, 550);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    @Override
    public void actionPerformed(ActionEvent arg0)
    {
        String command=arg0.getActionCommand();
        if(command.equals("第一张"))
        {
            ob=it.first(); 
            this.showPicture(ob.getName(),ob.getIntroduce());
        }
        else if(command.equals("下一张"))
        {
            ob=it.next(); 
            this.showPicture(ob.getName(),ob.getIntroduce());
        }
        else if(command.equals("上一张"))
        {
            ob=it.previous(); 
            this.showPicture(ob.getName(),ob.getIntroduce());
        }
        else if(command.equals("最末张"))
        {
            ob=it.last(); 
            this.showPicture(ob.getName(),ob.getIntroduce());
        }
    }
}
//婺源景点类
class WyViewSpot
{
    private String Name;
    private String Introduce;
    WyViewSpot(String Name,String Introduce)
    {
        this.Name=Name;
        this.Introduce=Introduce;
    }
    public String getName()
    {
        return Name;
    }
    public String getIntroduce()
    {
        return Introduce;
    }
}
//抽象聚合:婺源景点集接口
interface ViewSpotSet
{ 
    void add(WyViewSpot obj); 
    void remove(WyViewSpot obj); 
    ViewSpotIterator getIterator(); 
}
//具体聚合:婺源景点集
class WyViewSpotSet implements ViewSpotSet
{ 
    private ArrayList<WyViewSpot> list=new ArrayList<WyViewSpot>(); 
    public void add(WyViewSpot obj)
    { 
        list.add(obj); 
    }
    public void remove(WyViewSpot obj)
    { 
        list.remove(obj); 
    }
    public ViewSpotIterator getIterator()
    { 
        return(new WyViewSpotIterator(list)); 
    }     
}
//抽象迭代器:婺源景点迭代器接口
interface ViewSpotIterator
{
    boolean hasNext();
    WyViewSpot first();
    WyViewSpot next();
    WyViewSpot previous();
    WyViewSpot last(); 
}
//具体迭代器:婺源景点迭代器
class WyViewSpotIterator implements ViewSpotIterator
{ 
    private ArrayList<WyViewSpot> list=null; 
    private int index=-1;
    WyViewSpot obj=null;
    public WyViewSpotIterator(ArrayList<WyViewSpot> list)
    {
        this.list=list; 
    } 
    public boolean hasNext()
    { 
        if(index<list.size()-1)
        { 
            return true;
        }
        else
        {
            return false;
        }
    }
    public WyViewSpot first()
    {
        index=0;
        obj=list.get(index);
        return obj;
    }
    public WyViewSpot next()
    {         
        if(this.hasNext())
        { 
            obj=list.get(++index);
        } 
        return obj; 
    }
    public WyViewSpot previous()
    { 
        if(index>0)
        { 
            obj=list.get(--index); 
        } 
        return obj; 
    }
    public WyViewSpot last()
    {
        index=list.size()-1;
        obj=list.get(index);
        return obj;
    }
}

Result of the program shown in Figure 3.
 

                       Operating results Wuyuan scenic tourist map browsing program

Application of scene modes

The structure and characteristics of the front Iterated mode, the following describes the application scenario, normally used in an iterative mode following situations.

  1. When it is desired to provide a variety of ways to traverse the aggregate object.
  2. When it is desired to provide a unified interface when traversing different polymeric structure.
  3. When accessing a content object polymerization without exposing the details of its internal representation.


Because of polymerization and iterators are very close, so most language classes in achieving polymerization provides an iterator class, using the following language in the case of large numbers of existing polymerization iterator class had enough.

Extended mode

Iterative mode is often associated with combination patterns used in combination when the combination of the container member access mode, iterator often hidden in the container assembly configuration mode class. Of course, a configuration may also be accessed iterator external container member, the structure shown in Figure 4.
 

                 Iterative mode configuration diagram of the combination

 

Published 136 original articles · won praise 6 · views 1539

Guess you like

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