In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the example analysis of iterator pattern in Java design pattern, which is very detailed and has certain reference value. Friends who are interested must read it!
Introduction
Iterator pattern (Iterator Pattern): provides a way to access an aggregate object without exposing the internal representation of the object, alias Cursor. Iterator pattern is a kind of object behavior pattern.
Role
Iterator (abstract iterator): it defines interfaces for accessing and traversing elements, and declares methods for traversing data elements, such as the first () method for getting the first element, the next () method for accessing the next element, the hasNext () method for determining whether there is a next element, the currentItem () method for getting the current element, and so on, which will be implemented in the concrete iterator.
ConcreteIterator (concrete iterator): it implements the abstract iterator interface, completes the traversal of the aggregate object, and records the current position in the aggregate object through the cursor in the concrete iterator. In the concrete implementation, the cursor is usually a non-negative integer representing the position.
Aggregate (Abstract aggregation Class): it is used to store and manage element objects, declaring a createIterator () method to create an iterator object that acts as an abstract iterator factory.
ConcreteAggregate (concrete aggregate class): it implements the createIterator () method declared in the abstract aggregation class, which returns a concrete iterator ConcreteIterator instance corresponding to the concrete aggregation class.
In the iterator pattern, an external iterator is provided to access and traverse the aggregate object, the iterator defines an interface to access the aggregate element, and can track the elements currently traversed, to know which elements have been traversed and which have not. The introduction of iterators will make it easier to manipulate a complex aggregate object.
Factory pattern in iterator pattern
The factory method pattern is applied in the iterator pattern, the abstract iterator corresponds to the abstract product role, the concrete iterator corresponds to the specific product role, the abstract aggregation class corresponds to the abstract factory role, and the concrete aggregation class corresponds to the concrete factory role.
Cases traversed by the college
Write a program to show the structure of a school: the need is to show the composition of the school's departments on one page, with multiple colleges in one school and multiple departments in one college.
Analysis.
Every college has the function of adding departments if we write the traversal method hasNext () next () and so on. This will cause the aggregate class to be overburdened, which is responsible for both storing and managing data and traversing the data, violating the "single responsibility principle". Because the aggregation class is very large and the implementation code is too long, it will also make testing and maintenance more difficult.
At this time, we may think like this, because there are multiple colleges, we might as well encapsulate the institute as an interface, but this interface is full of methods, which is not conducive to subclass implementation and violates the principle of interface isolation.
Solution
One of the solutions is to extract the method responsible for traversing the data in the aggregation class, encapsulate it into a special class, separate data storage and data traversal, and operate it without exposing the internal properties of the aggregation class. and that's what the iterator pattern is all about.
Basic introduction
Iterator pattern (Iterator Pattern) is a commonly used design pattern, which belongs to behavioral pattern.
If our collection elements are implemented in different ways, there are arrays, there are java collection classes, or there are other ways, when the client wants to traverse these collection elements, it will use a variety of traversal methods, but also expose the internal structure of the elements, you can consider using the iterator pattern.
Iterator pattern provides a unified interface for traversing collection elements, traversing collection elements in a consistent way, without knowing the underlying representation of the collection object, that is, without exposing its internal structure.
Principle class diagram
The class diagram of the above case
Case implementation code
The top-level iterator interface is the Iterator interface provided inside Java:
The computer school iterator class, which is responsible for traversing the collection of departments under the computer school class
Public class ComputerCollegeIterator implements Iterator {/ / stores each department under the computer school private Department [] departments; / / the current traversal location private Integer position=0; / / obtains the collection to be traversed through the constructor public ComputerCollegeIterator (Department [] departments) {this.departments=departments as an array } / / determine whether the next element @ Override public boolean hasNext () {if (position > departments.length-1 | | departments [position] = = null) {return false;} return true;} / / returns the next element @ Override public Object next () {return departments [position++] The method to delete @ Override public void remove () {}} is empty by default.
The information school iterator class, which is responsible for traversing the collection of departments under the information school
/ / School of Information public class InfoCollegeIterator implements Iterator {/ / store the department private List departments; / / index private Integer index=0; / / constructor in the way of list to get the collection InfoCollegeIterator (List departments) {this.departments=departments to be traversed } / / determine whether there is another element in the list collection @ Override public boolean hasNext () {if (index > departments.size ()-1) {return false;} return true;} @ Override public Object next () {return departments.get (index++);} @ Override public void remove () {}}
The iterator classes of the corresponding colleges here are separately responsible for traversing the logic of the collection of departments under the current college.
The optimization measures here can extract the duplicates from the two iterators and put them into the CollegeIterator class for default implementation, which inherits the Iterator interface, while the above two academic iterator classes inherit the default implementation class.
The iterator iterates through the elements stored in the collection:
The departments under @ Data@AllArgsConstructor@NoArgsConstructor// College-- also the objects that the iterator needs to traverse-- public class Department {private String name;// name private Integer score;// fractional line}
Top-level Abstract Academy Interface
/ / Abstract Academy API public interface College {/ / get the name of the current department void getName (); / / add the department void addDepartment (String name,Integer score); / / return an iterator responsible for traversing Iterator createIterator ();}
The departments under the School of computer Science and Management
The default size of public class ComputerCollege implements College {/ / array is 10 private Department [] departments=new Department [10]; the number of objects saved in the current array of private Integer numOfDepartment=0;// @ Override public void getName () {System.out.println ("computer Academy");} / / get the corresponding department set public ComputerCollege (Department [] departments) {int item0 For (Department department: departments) {this.departments [iTunes +] = department;}} / / add @ Override public void addDepartment (String name,Integer score) {Department department=new Department (name,score); departments [numOfDepartment++] = department;} / / create the corresponding iterator and pass the collection to be traversed to the iterator @ Override public Iterator createIterator () {return new ComputerCollegeIterator (departments);}}
School of Information, responsible for managing the following departments:
/ / School of Information public class InfoCollegeIterator implements Iterator {/ / stores the department private List departments; / / index private Integer index=0; InfoCollegeIterator (List departments) {this.departments=departments;} / / to determine whether there is another element in the list collection @ Override public boolean hasNext () {if (index > departments.size ()-1) {return false. } return true;} @ Override public Object next () {return departments.get (index++);} @ Override public void remove () {}}
Output class, mainly responsible for output function:
Public class OutputImp {/ / College set private List collegeList; public OutputImp (List collegeList) {this.collegeList=collegeList;} / / output all colleges and all departments under the college public void printColleges () {/ / get the iterator / / list collection needed to traverse the college collection and implement the iterator interface Iterator collegeIterator = collegeList.iterator () While (collegeIterator.hasNext ()) {College college = collegeIterator.next (); System.out.println ("current College:"); college.getName (); System.out.println ("departments under the current College:") / / if you want to traverse all the departments under the current college, you need to get the corresponding iterator printDeparts (college.createIterator ()); System.out.println ("= =");}} / / output all the departments of the current college protected void printDeparts (Iterator iterator) {while (iterator.hasNext ()) {Department department= (Department) iterator.next () System.out.println (department.getName ());}
The client calls:
Public static void main (String [] args) {List collegeList=new ArrayList (); Department [] departments=new Department [3]; departments [0] = new Department ("C++", 520); departments [1] = new Department ("java", 521); College college=new ComputerCollege (departments); List departmentList=new ArrayList (); departmentList.add (new Department (Cryptography, 520); College college1=new InfoCollege (departmentList) CollegeList.add (college); collegeList.add (college1); OutputImp outputImp=new OutputImp (collegeList); outputImp.printColleges ();}
Case summary
If you need to add a new concrete aggregate class, you only need to add a new aggregation subclass and a new concrete iterator class. The original class library code does not need to be modified and accords with the "opening and closing principle".
If you need to replace an iterator for the aggregate class, you only need to add a new concrete iterator class as a subclass of the abstract iterator class and re-implement the traversal method. The original iterator code does not need to be modified and conforms to the "opening and closing principle".
However, if you want to add new methods to the iterator, you need to modify the abstract iterator source code, which will violate the "open-close principle".
The iterator pattern in the application instance Java collection
Look at the java.util.ArrayList class
Public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, java.io.Serializable {transient Object [] elementData; / / non-private to simplify nested class access private int size; public E get (int index) {rangeCheck (index); return elementData (index);} public boolean add (E) {ensureCapacityInternal (size + 1); / / Increments modCounting! ElementData [size++] = e; return true;} public ListIterator listIterator () {return new ListItr (0);} public ListIterator listIterator (int index) {if (index)
< 0 || index >Size) throw new IndexOutOfBoundsException ("Index:" + index); return new ListItr (index);} public Iterator iterator () {return new Itr ();} private class Itr implements Iterator {int cursor; / / index of next element to return int lastRet =-1; / / index of last element returned;-1 if no such int expectedModCount = modCount Public boolean hasNext () {return cursor! = size } public E next () {/ /...} public E next () {/ /...} public void remove () {/ /...} / /.} private class ListItr extends Itr implements ListIterator {public boolean hasPrevious () {return cursor! = 0 } public int nextIndex () {return cursor;} public int previousIndex () {return cursor-1 } public E previous () {/ /...} public void set (E) {/ /...} public void add (E) {/ /...} / /.}
From the ArrayList source code, you can see that there are two iterators, Itr and ListItr, which implement the Iterator and ListIterator interfaces respectively.
The first one is of course easy to see, the difference between it and our example iterator is that it is an inner class that can directly use ArrayList's data list; the second iterator is the first to see, what's the difference between ListIterator and Iterator?
First take a look at the ListIterator source code
Public interface ListIterator extends Iterator {boolean hasNext (); E next (); boolean hasPrevious (); / / returns whether there is a previous element E previous () in the collection associated with the iterator; / / returns the previous element int nextIndex () of the iterator; / / returns the index int previousIndex () of the elements behind the ListIterator desired position in the list / / returns the index void remove (); void set (E var1); / / changes the last element returned by next () or previous () from the list to the specified element e void add (E var1);}
Then there is the source code of Iterator
Public interface Iterator {boolean hasNext (); E next (); default void remove () {throw new UnsupportedOperationException ("remove");} / / Note: JAVA8 allows interface methods to define the default implementation default void forEachRemaining (Consumer)
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.