Iterator pattern and the use of inner classes
(a) The previous article wrote about the role of static, in part by introducing inner classes and static inner classes, and the following is an introduction to the benefits of inner classes in the context of the iterator pattern in design patterns.
1.To begin with the role of internal classes will be stated.
First, the internal class can directly access the external class of things, if there is no internal class, to implement the iterator pattern, there are 2 ways, first, in the container class to define some methods, then you need to define some global member variables to record the cursor and so on some data, resulting in a cumbersome container class, not easy to extend. Second, creating an iterator class on a level with the container class requires class-to-class communication, raising the coupling between the container class and the iterator class.
Internal classes, on the other hand, have direct access to the member variables and member functions of the container class, and the internal classes simply implement their own methods.
Another advantage is that, as one commenter said, ArrayList's inner class ArrayIterator is rarely reused by other classes, which is why they designed it as an inner class, and it's not a good idea to design it as an inner class if it's going to be reused a lot by other classes, even with all its "advantages". HashMap's internal class Entry is typically designed for this reason, the first is that it wants to use the external class Entry are not available, there is already a class of the same name, and it so happens that HashMap's Entry is also basically only HashMap itself will use, that just designed as an internal class.
2.Benefits of the iterator pattern.
II. UML diagrams