Design Pattern-Implementation of iterator Pattern

Source: Internet
Author: User
Tags concurrentmodificationexception

Introduction: the software design model is a new method for expressing, recording, and reusing the software design structure and design experience. It identifies, abstracts, and names the key features of repeated design structures, it makes it easier to reuse the successful design and structure. This article introduces the features and descriptions of the software design pattern and the benefits of the pattern used in the design, and introduces the Java Collection framework (javacollectionframework) for the iterator pattern) the typical implementation in is

For example, the implementation method of this mode and the convenience of software expansion and use brought by this mode are described. The iterator mode separates the traversal behavior of the set object and abstracts an iterator class to take charge of it, so that the internal structure of the set is not exposed, in addition, external code can transparently access the internal data of the set.
Key words: Design Mode iterator mode Java set framework class

0
With the rapid development and wide application of computer networks and communications, the market has put forward almost stringent requirements on enterprise software capabilities. Improving Software capabilities to resolve the software crisis has become a top priority for the software industry .. Componentization and reuse are the successful experiences of more than 200 years of industrial society development. Drawing on the successful experiences of industrial society development, it is very important to determine feasible software industrialization goals. Componentization and reuse are essential ways to improve software capabilities. The software design pattern is a new method to express, record, and reuse the software design structure and design experience. It identifies, abstracts, and names the key features of repeated design structures, it makes it easier to reuse the successful design and structure. Software design patterns have become an important research object of modern software system design .. This article introduces the features and descriptions of the software design pattern and the benefits of the pattern used in the design.
Collection framework.
1. Design Mode
The idea of the design pattern originally came from the architectural field, but the thought embodied in it also applies to other fields, such as the object-oriented software design field. The design model focuses on specific design problems and their solutions. Each model describes a design problem and a verified and general solution, this solution identifies and abstracts repeated design structures. It generally consists of multiple objects. In a pattern, it not only describes the design of objects, but also describes the communication between objects.
A design pattern has four basic elements:
Pattern name: a nickname. It uses one or two words to describe pattern problems, solutions, and effects.
Problem: Describes when to use this mode.
Solution: describes the components of the design, the relationships between them, their respective responsibilities, and the way they work together.
Consequences describes the effects and usage modes of a pattern application.

[Www.uuubuy.com. The effects of a pattern include its impact on system flexibility, scalability, or portability. explicitly listing these effects is helpful for understanding and evaluating these patterns.
Based on the different issues, the design patterns can be divided into three types: Creation patterns, structural patterns, and behavior patterns.
The creation mode is related to how to effectively create class instances. These modes allow the program to create specific classes according to specific situations. You can use new to create an instance and only generate a fixed class in the program. However, in many cases, the program needs to generate instances of different classes according to different situations. This requires abstracting the instance generation process to a special creation class, this class determines the type of instances to be generated during running. This makes the program more flexible and universal.
The structure mode processes the combination of classes and objects, and combines classes and objects to form a more complex structure. It is also divided into class mode and object mode. The difference between the class mode and the object mode is that the class mode provides valid interfaces through the inheritance relationship; the object mode forms a more complex structure behavior mode by merging objects or including objects in other objects,
The behavior type pattern mainly refers to the pattern that processes communication between objects. It describes interaction and Responsibility Assignment of classes or objects, and defines communication between objects and Flow Control in complex programs. The iterator pattern involved in this article is a behavior pattern.
2. iterator Pattern)
In the object-oriented software design, we will encounter a class of set objects. The implementation of the internal structure of these set objects may vary greatly, but we need to focus on only two points: the first is the data storage structure inside the set, and the second is to traverse the data inside the set. The single responsibility principle is an important principle of object-oriented design. Therefore, we should try our best to break down these responsibilities and use different classes to assume different responsibilities. The iterator mode separates the traversal behavior of the set object and abstracts an iterator class to take charge of it, so that the internal structure of the set is not exposed, in addition, external code can transparently access the internal data of the set.
The intent of the iterator is to provide a method to access each element in a set object sequentially without exposing the internal details of the object. For the current TV set, use the [next] and [previous] buttons to switch the channel. When you press the [next] button, it switches to the next preset channel. As TV users, when we change channels, we are not concerned about specific channels.

But the program content. If you are not interested in the program of a channel, you can switch to the next channel without knowing the specific channel, figure 1 shows an object chart that uses the channel iterator to select servers. Figure 1 iterator mode using the selector as an example object graph iterator mode adds the iterator role between the customer and the container. It can abstract the access logic from a collection class of the same type to avoid

Expose the internal structure of the collection on the client .. The client itself does not maintain the "Pointer" of the traversal set. All internal states (such as the current element location and whether there is any next element) are maintained by the iterator. The client never directly deals with the collection class, it always controls the iterator and sends the "forward", "backward", "Get current element" command to it to indirectly traverse the entire set.
In order to remove the customer program from the dilemma of coupling with a specific iterator and avoid modifications to the customer program due to the replacement of the specific iterator, The iterator pattern abstracts the specific iterator, this makes the customer program more general and reusable.
The iterator mode structure 2 is shown below:
  
Figure 2 iterator mode structure
It can be seen from the structure that the iterator mode consists of the following roles: the iterator role (iterator), which defines the interface for accessing and traversing elements; the specific iterator role (concrete iterator ), implement the iterator interface and record the current position in the traversal. The Container role (container) is responsible for providing the interface for creating a specific iterator role. The Container role (concrete container ), implement the interface for creating a specific iterator role, which is related to the structure of the container.
By adding the iterator role, you can avoid the exposure of the internal details of the container, and make the design comply with the "single responsibility principle ". The specific iterator role is coupled with the specific container role, that is, the traversal algorithm is closely related to the internal details of the container.
3. Implementation of the iterator mode in the Java class library
The Java class library is a classic application of the design pattern. Here we take the Java Collection framework in the Java class library as an example to discuss the implementation of the iterator pattern.
In Java Collection framework applications, traversal processes are controlled by customer programs. This implementation method is called an external iterator; it is more flexible and powerful than the internal iterator controlled by the iterator itself.
The implementation of Traversal Algorithms should be implemented in the iterator role on the surface. In this way, different Traversal Algorithms can be used on a container, and a traversal algorithm can be applied to different containers. In this case, the container role is required to expose its own private attributes, thus damaging the container encapsulation. Therefore, the traversal algorithm is implemented in the container role. In this way, the traversal algorithm is bundled with a specific container, and the iterator role is only stored.

[Www.uuubuy.com] indicates the current position of the traversal. Another advantage of doing so is that the same container object can be traversed at the same time. Because the traversal status is saved in each iterator object. In Java Collection framework applications, the specific iterator role is defined in the internal class of the container role, which protects the container encapsulation. At the same time, containers also provide traversal algorithm interfaces to expand their respective iterators.
The following section describes the code snippets corresponding to the four roles in the iterator mode in the javacollection framework of JDK, so as to analyze how the iterator mode is implemented in the Java Collection framework, figure 3 shows the class diagram of the basic classes to be analyzed:
  
Figure 3 basic class diagram in Java Collection framework
1) The iterator role and interface iterator define the traversal interface,
Code snippet 1
Public interfaceiterator <E> {
Boolean hasnext ();
E next ();
Void remove ();
}
2) Container role, interface list.
3) The specific container role implements the list interface and inherits the arraylist class of the abstract class abstractlist.
4) The specific iterator role is in the form of an internal class of the abstract class abstractlist. Abstract class abstractlist exists to extract the public part of each specific container role.
The iterator () method shown in code snippet 2 is the factory method for creating a specific iterator role.
Code snippet 2:
Publiciterator <E> iterator (){
Return new itr ();
}
As a specific iterator role of an internal Class, Class 4 shows the specific implementation code, as shown in code segment 3.
  
Figure 4 role color chart of a specific iterator
Code snippet 3:
Private class itrimplements iterator <E> {
Intcursor = 0;
Intlastret =-1;
Intexpectedmodcount = modcount;
Publicboolean hasnext (){
Return cursor! = Size ();
}
Publice next (){
Checkforcomodification ();
Try {

E next = get (cursor)

; Lastret = cursor ++; return next;} catch (indexoutofboundsexception e) {checkforcomodification (); throw new nosuchelementexception () ;}} publicvoid remove () {If (lastret =-1) throw new illegalstat

Eexception ();
Checkforcomodification ();
Try {
Abstractlist. This. Remove (lastret );
If (lastret <cursor) cursor --;
Lastret =-1;
Expectedmodcount = modcount;
} Catch (indexoutofboundsexception e ){
Throw new concurrentmodificationexception ();
}
}
Finalvoid checkforcomodification (){
If (modcount! = Expectedmodcount)
Throw new concurrentmodificationexception ();
}
}
The usage of the iterator mode is shown in code segment 4 below. The customer program first obtains the specific container role, and then obtains the specific iterator role through the specific container role. In this way, you can use the specific iterator role to traverse the container.
Code snippet 4
List <E>

[Www.uuubuy.com] list = new arraylist <E> ();
Iterator it = List. iterator ();
While (it. hasnext ()){
It. Next (); // do some businesss Logic
}
4. Summary
The iterator mode is widely used in applications. It abstracts an iterator class responsible for Traversing behavior to achieve the internal structure of the set without exposing it, and allows external code to transparently access the internal data of the set.
When implementing your own iterator, the container to be operated must have corresponding interface support. By adding the corresponding internal iterator class in the container, You can traverse the specific container, there are also factory methods for creating specific iterator roles. Of course, the traversal meanings and implementations of container roles with different structures are also quite different, especially when there are complex objects or data structures in containers, it is worth noting how to perform deep traversal and the security of traversal.

[Contributions]
[1] (US) gof. Design Model-Basis of reusable object-oriented software, Mechanical Industry Press, 2005.
[2] The Java design pattern, http://www.cn-java.com.
[3]. net design pattern, http://www.cnblogs.com.
[4] ripple. Java design model, people's post and telecommunications Press, 2007.
[5] Rao Yimei, Wang Zhibao, and Wang xiufeng. The Software Design Pattern and Its typical implementation in the Java class library. [J] Computer Engineering and application, 2002/4, P48-50.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.