Iterator pattern -Iterator Pattern

table of Contents

The definition and characteristics of the model

Architecture and Implementation Model

Mode of application examples

Application of scene modes

Extended mode


In real life, as well as programming, often want to access a target in the various elements of the polymerization, the usual practice is to create a linked list traversal and are placed in the same class, but this approach is not conducive to the extension, if you want to replace traversal methods must be modified source code, which is contrary to the "on-off principle."

In software development, we often need to use objects to store a series of data aggregation. Aggregate object has two functions: one for storing data; the second is through the data. From the view-dependent, the former is the basic duty aggregate object; the latter can only change is separable. Thus, the behavior through the data can be separated out from the aggregate object, a package called "iterative" on the object to traverse the act of providing the data within the object by polymerization iterator, which will simplify the design of the aggregate object , more in line with "single responsibility principle" requirements.

"Iterative mode", which is interposed between the client-based access to a polymerization iterator class, which separates the aggregate object and its traversal behavior, the customer also hides its internal details, and satisfies a "single principle function" and "on-off principles "such as  J AVA 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. (It supports different ways to traverse an aggregate object, the same object can define a variety of polymeric traversal. Just use a different iterator to replace the original iterator Iterator mode to change the traversal algorithm, we can also define their own iterator subclass to support the new way to navigate.
  2.  Iterator class simplifies the polymerization. Since the introduction of the iterators, the polymerization in the original data object does not need to provide their own traversal method, which can simplify the design of the polymerization class.
  3. In the iterative mode, since the introduction of abstraction layer, and add a new class of polymerizable iterator class easy, without having to modify existing code to meet the requirements of "opening and closing principle".


The main disadvantages are:

(1) Since the separation of duties iterative mode and stores data through the data, adding new classes need a corresponding increase in new polymerization iterator class, the class number of pairs increases, which increases the complexity of the system to some extent, .

(2) the difficulty of design abstraction iterator large, need to fully take into account the future expansion of the system, such as the built-in JDK iterator Iterator reverse traversal can not be achieved, if the need to implement a reverse traversal, can only be achieved through its subclasses ListIterator etc. ListIterator iterator can not be used while the operation of the aggregate object type Set. When a custom iterator, create a comprehensive consideration of abstract iterator it is not an easy thing.

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, 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
Iterative mode structure of FIG. 1 FIG.

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

Write a scenic view map of Wuyuan tourism program with the iterator pattern.

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
Figure 2 structure 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;
    }
}
程序运行结果如图 3 所示。

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 used in combination with the combination mode 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
FIG 4 a configuration diagram of the iterative mode combination

Guess you like

Origin blog.csdn.net/yucaixiang/article/details/95040566