[design mode from introduction to mastery] 15 - iterator mode

Note source: Shang Silicon Valley Java design pattern (illustration + framework source code analysis)

Iterator mode

1. School department structure display demand

Write a program to display the department structure of a school. You should display the Department composition of the school on one page. A school has multiple colleges and a college has multiple departments. As shown in the figure:

Traditional scheme analysis

  • 1) The college is regarded as a subclass of the school, and the Department is a subclass of the college. In fact, it is hierarchical based on the size of the organization
  • 2) In fact, our requirement is to display the composition of the school's departments in one page. A school has multiple colleges and a college has multiple departments. Therefore, this scheme can not well realize the traversal operation
  • 3) Solution: iterator mode

2. Basic introduction

  • 1) Iterator pattern is a common design pattern, which belongs to behavioral pattern
  • 2) If our collection elements are implemented in different ways, there are arrays, collections or other ways. When the client wants to traverse these collection elements, it needs to use a variety of traversal methods, and it will expose the internal structure of the elements. It can be solved by using the iterator pattern
  • 3) Iterator mode provides a unified interface for traversing set elements. It traverses set elements in a consistent way without knowing the underlying representation of set objects, that is, it does not expose its internal structure

Schematic class diagram

Roles and responsibilities of iterator pattern

  • Iterator iterator interface: provided by the system, including hasNext, next and remove
  • Concrete iterator concrete iterator: manage related iterations
  • Aggregate aggregation interface: decouples the client from the concrete aggregation
  • ConcreteAggregate concrete aggregate class: provides a method that returns an iterator that can traverse the collection correctly
  • Client client: depends on its specific Iterator and aggregation subclass through Iterator iterator interface and Aggregate aggregation interface

3. The iterator completes the display requirements of school department structure

UML class diagram

Core code

Concrete iterator

/**
 * Computer iterator class
 */
public class ComputerCollegeIterator implements Iterator {
    private Department[] departments;
    private Integer position = -1;

    public ComputerCollegeIterator(Department[] departments) {
        this.departments = departments;
    }

    @Override
    public boolean hasNext() {
        return position + 1 < departments.length && departments[position + 1] != null;
    }

    @Override
    public Object next() {
        return departments[++position];
    }
}
/**
 * Information iterator class
 */
public class InfoCollegeIterator implements Iterator {
    private List<Department> departments;
    private Integer position = -1;

    public InfoCollegeIterator(List<Department> departments) {
        this.departments = departments;
    }

    @Override
    public boolean hasNext() {
        return position + 1 < departments.size();
    }

    @Override
    public Object next() {
        return departments.get(++position);
    }
}

Aggregation interface

public interface College {
    String getName();
    
    Iterator<Department> createIterator();
}

Concrete aggregate class

/**
 * school of computing
 */
public class ComputerCollege implements College {
    private Department[] departments;
    private Integer position = 0;

    public ComputerCollege() {
        departments = new Department[5];
        departments[position++] = new Department("Java major");
        departments[position++] = new Department("PHP major");
        departments[position++] = new Department("Python major");
    }

    @Override
    public String getName() {
        return "school of computing";
    }

    @Override
    public Iterator<Department> createIterator() {
        return new ComputerCollegeIterator(departments);
    }
}
/**
 * School of information
 */
public class InfoCollege implements College {
    private List<Department> departments;

    public InfoCollege() {
        departments = new ArrayList<>();
        departments.add(new Department("Information Security Major"));
        departments.add(new Department("Network security major"));
        departments.add(new Department("Server security"));
    }

    @Override
    public String getName() {
        return "School of information";
    }

    @Override
    public Iterator<Department> createIterator() {
        return new InfoCollegeIterator(departments);
    }
}

Output class

public class OutPutImpl {

    public OutPutImpl() {
    }

    public void printCollege(List<College> collegeList) {
        Iterator<College> iterator = collegeList.iterator();
        while (iterator.hasNext()) {
            College college = iterator.next();
            System.out.println("============" + college.getName() + "============");
            printDepartment(college);
        }
    }

    private void printDepartment(College college) {
        Iterator<Department> iterator = college.createIterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next().getName());
        }
    }
}

Call test

List<College> collegeList = new ArrayList<>();
collegeList.add(new ComputerCollege());
collegeList.add(new InfoCollege());
new OutPutImpl().printCollege(collegeList);

Print results

//============Computer College============
//Java major
//PHP major
//Python major
//============School of information============
//Information Security Major
//Network security major
//Server security

4. ArrayList collection source code analysis

UML class diagram

Role analysis description

  • Iterator iterator interface: it is provided by the system and defines methods such as hasNext() and next()
  • Itr specific Iterator implementation class: it exists as an internal class of ArrayList and implements the methods such as hasNext() and next() of the Iterator interface
  • List aggregation interface: defines the iterator() method and returns an iterator interface object
  • The specific aggregation class of ArrayList: implements the iterator() method

The iterator pattern provides a unified Traversal Solution for different collection types (such as ArrayList, LinkedList, etc.)

5. Considerations and details of iterator pattern

advantage

  • 1) Provide a unified method to traverse objects. Customers can traverse objects using one method without considering the type of aggregation
  • 2) The internal structure of aggregation is hidden. When the client wants to traverse the aggregation, it can only get the iterator without knowing the specific composition of the aggregation
  • 3) It provides a design idea that a class should have only one cause of change (single responsibility principle). In the aggregation class, we separate iterators to separate the responsibility of managing the object collection and traversing the object collection. In this way, if the collection changes, it will only affect the aggregation object. If the traversal mode changes, only the iterator is affected
  • 4) When you want to show a group of similar objects or traverse a group of the same objects, it is suitable to use the iterator pattern

shortcoming

  • Each aggregate object needs an iterator, which will generate multiple iterators, which is difficult to manage

Keywords: Design Pattern

Added by _confused_ on Tue, 04 Jan 2022 01:41:11 +0200