Java is undoubtedly one of the most successful projects, and in which learning design patterns and architecture design is undoubtedly the best.
Concept:
Provides a way to access individual elements in a container without exposing the internal details of the object.
Usage scenarios:
And the container is often together, we define a container, but also to provide external access to the method, the iterator pattern is undoubtedly the best.
UML class diagrams for the iterator pattern:
The following code is a lite version of the implementation iterator pattern inside the Java Collection framework:
Public Interface Iterator<e> {//Iterator Interface Lite version boolean hasnext (); E next ();}
Public Interface List<e> {//Container interface Lite version Iterator<E> Iterator ();}
Public classArraylist<e>ImplementsList<e> { Privateobject[] Array; PublicArrayList () { This. array=NewObject[5]; This. array[0]= "A"; This. array[1]= "B"; This. array[2]= "C"; This. array[3]= "D"; This. array[4]= "E"; } PublicIterator<e>iterator () {return NewArrayiterator (); } Public class Arrayiterator ImplementsIterator<e>{ Private intCursor=0; Public BooleanHasnext () {if(cursor<array.length) { return true; } return false; } @SuppressWarnings ("Unchecked") Publice Next () {e e= (E) array[cursor++]; returne; } }}
Benefits of the Inner class:
If there is no inner class, to implement the iterator pattern, there are 2 ways, first, in the container class to define some methods, it is necessary to define some global member variables to record the cursor and so on some data, resulting in container classes cumbersome, not easy to expand. Second, establishing an iterator class with the container class, which requires communication between classes and classes, enhances the coupling between the container class and the iterator class.
The inner class, however, can directly access the member variables and member functions of the container class, and the inner class simply implements its own method.
I think that in a class, simple member variables and member functions can not meet the increasingly complex requirements, sometimes, the concept inside the class also needs variables and functions, I believe this is the meaning of the inner class.
If you want to wear a crown, it will be heavy.
Java source code-iterator mode