[Java design pattern] Java design pattern (eight) iterator pattern (Iterator Pattern)

Contents of this article

1. Overview of iterators

1.1 Advantages and disadvantages

1.2 Usage scenarios

1.3 Matters needing attention

Second, the code implementation

2.1 General Class Diagram

2.2 Code implementation


Iterator Pattern (Iterator Pattern) is a very commonly used design pattern in Java and .Net programming environments. The iterator pattern is a behavioral pattern. This mode is used to sequentially access the elements of the collection object without knowing the underlying representation of the collection object.

1. Overview of iterators

Intent: Provide a way to sequentially access the elements in an aggregated object without exposing the internal representation of the object.

The main solution: different ways to traverse the entire integration object.

When to use: Traverse an aggregate object.

How to solve it: Give the responsibility of walking between elements to the iterator instead of the aggregate object.

Key code: Define the interface: hasNext, next.

Application example: iterator in JAVA.

1.1 Advantages and disadvantages

Advantages: 1. It supports traversing an aggregate object in different ways. 2. The iterator simplifies the aggregation class. 3. There can be multiple traversals on the same aggregation. 4. In the iterator mode, it is very convenient to add new aggregation classes and iterator classes, without modifying the original code.

Disadvantages: Since the iterator mode separates the responsibilities of storing data and traversing data, adding new aggregate classes requires corresponding new iterator classes, and the number of classes increases in pairs, which increases the complexity of the system to a certain extent.

1.2 Usage scenarios

Usage scenarios: 1. Access the content of an aggregated object without exposing its internal representation. 2. It is necessary to provide multiple traversal methods for aggregated objects. 3. Provide a unified interface for traversing different aggregation structures.

1.3 Matters needing attention

Note: The iterator pattern separates the traversal behavior of the collection object and abstracts an iterator class to be responsible. This not only does not expose the internal structure of the collection, but also allows external code to transparently access the data inside the collection.

Second, the code implementation

The code implementation examples of all design patterns can be viewed on Code Cloud, and those who are interested can check it. Code Cloud address: https://gitee.com/no8g/java-design-patterns


2.1 General Class Diagram

The above example uses the iterator pattern. Let's take a look at the general class diagram of iterators:

 

The class diagram is very simple, but it seems to be very troublesome to use. For example, the two implementation methods in the above example, which one do you think is simple? Of course it is the first one! The 23 design patterns are to simplify the complexity and coupling degree of our code and design. Why do we use this iterator pattern program to be more complicated? Why is that? Since the java.util.Iterator interface has been added since the JDK 1.2 version, and iterator has been gradually applied to various collections (Collection), we look at the API help file of JDK 1.5, and you will see that there is a java.util. Iterable interface, see how many interfaces inherit it:

The java.util.Iterable interface has only one method: iterator(), that is to say, iterator() is used to traverse all methods or attributes in the aggregate class. Basically all high-level languages ​​now have the Iterator interface or implementation. Java has already prepared iterators for us. Let's write iterators. Isn't it "six fingers scratching it, one more one"? So, this iterator mode is also a bit of a decline. Basically, there are few projects that write iterators independently. You can solve the problem completely by using List or Map directly.

2.2 Code implementation

package com.iot.practice.designpattern.iterator.iteratorpattern;

import java.util.Iterator;

/**
 * <p>IProjectIterator 此接口用于:</p>
 * <p>@author:hujm</p>
 * <p>@date:2021年02月23日 15:26</p>
 * <p>@remark:
 * 大家可能很奇怪,你定义的这个接口方法、变量都没有,有什么意义呢?有意义,所有的 Java 书上都一直
 * 说是面向接口编程,你的接口是对一个事物的描述,也就是说我通过接口就知道这个事物有哪些方法,哪些属性,
 * 我们这里的 IProjectIterator 是要建立一个指向 Project 类的迭代器,目前暂时定义的就是一个通用的迭
 * 代器,可能以后会增加 IProjectIterator 的一些属性或者方法。当然了,你也可以在实现类上实现两个接口,
 * 一个是 Iterator,一个是 IProjectIterator(这时候,这个接口就不用继承 Iterator),杀猪杀尾巴,
 * 各有各的杀发。
 * </p>
 */
public interface IProjectIterator extends Iterator {
}
package com.iot.practice.designpattern.iterator.iteratorpattern;

/**
 * <p>IProject 此接口用于:</p>
 * <p>@author:hujm</p>
 * <p>@date:2021年02月23日 15:15</p>
 * <p>@remark:</p>
 */
public interface IProject {
    /**
     * 增加项目
     *
     * @param name 项目名称
     * @param num 项目成员数量
     * @param cost 项目费用
     */
    public void add(String name,int num,int cost);

    /**
     * 从老板这里看到的就是项目信息
     *
     * @return 项目信息
     */
    public String getProjectInfo();

    /**
     * 获得一个可以被遍历的对象
     *
     * @return 一个可以被遍历的对象
     */
    public IProjectIterator iterator();
}
package com.iot.practice.designpattern.iterator.iteratorpattern;

import java.util.ArrayList;

/**
 * <p>Project 此类用于:</p>
 * <p>@author:hujm</p>
 * <p>@date:2021年02月23日 15:17</p>
 * <p>@remark:</p>
 */
public class Project implements IProject{
    /**
     * 定义一个项目列表,说有的项目都放在这里
     */
    private ArrayList<IProject> projectList = new ArrayList<IProject>();

    /**
     * 项目名称
     */
    private String name = "";

    /**
     * 项目成员数量
     */
    private int num = 0;

    /**
     * 项目费用
     */
    private int cost = 0;

    public Project(){}

    private Project(String name, int num, int cost) {
        // 赋值到类的成员变量中
        this.name = name;
        this.num = num;
        this.cost = cost;
    }

    @Override
    public void add(String name, int num, int cost) {
        this.projectList.add(new Project(name, num, cost));
    }

    @Override
    public String getProjectInfo() {

        String info = "";

        //获得项目的名称
        info = info+ "项目名称是:" + this.name;
        //获得项目人数
        info = info + "\t项目人数: "+ this.num;
        //项目费用
        info = info+ "\t 项目费用:"+ this.cost;

        return info;
    }

    @Override
    public IProjectIterator iterator() {
        return new ProjectIterator(this.projectList);
    }
}
package com.iot.practice.designpattern.iterator.iteratorpattern;

import java.util.ArrayList;

/**
 * <p>ProjectIterator 此类用于:</p>
 * <p>@author:hujm</p>
 * <p>@date:2021年02月23日 15:27</p>
 * <p>@remark:定义一个迭代器</p>
 */
public class ProjectIterator implements IProjectIterator {

    /**
     * 所有的项目都放在这里ArrayList中
     */
    private ArrayList<IProject> projectList = new ArrayList<IProject>();

    private int currentItem = 0;

    /**
     * 构造函数传入projectList
     *
     * @param projectList 所有项目集合
     */
    public ProjectIterator(ArrayList<IProject> projectList) {
        this.projectList = projectList;
    }

    /**
     * 判断是否还有元素,必须实现
     *
     * @return 是否为true
     */
    @Override
    public boolean hasNext() {
        // 定义一个返回值
        boolean b = true;
        if (this.currentItem >= projectList.size() || this.projectList.get(this.currentItem) == null) {
            b = false;
        }
        return b;
    }

    /**
     * 取得下一个值,必须实现
     *
     * @return 下一个值
     */
    @Override
    public IProject next() {
        return this.projectList.get(this.currentItem++);
    }
}

 

 

 

end!

Guess you like

Origin blog.csdn.net/weixin_44299027/article/details/114010693