Android app development and design pattern Article 1: iterator Pattern

Source: Internet
Author: User

Iterator pattern: provides a method to access each element of an aggregate object sequentially without exposing the internal representation of the object.

The iterator mode can be used to traverse a collection. Java also provides a tool class: Java. util. iterator <E>, similar.

1. When you need to access a clustered object, regardless of what these objects require, you should consider using the iterator mode.

2. When multiple traversal methods are required for clustering objects, you can use the iterator mode.

3. The iterator mode is widely used when accessing arrays, sets, lists, and other data, especially database data operations,

Therefore, various advanced languages have encapsulated it. Instead, it gives people the feeling that this mode is not commonly used.

4. Easy to save the traversal status and traverse multiple data

 

Scenario requirements

There are five technical books on the shelf. The names of these books must be traversed to display them on andriod's edittext. The preceding requirements are used as an example to describe the specific requirements as follows:

 

Aggregate Interface

The aggregate interface is an incremental "aggregation ". Classes that implement this interface become "Aggregation" similar to arrays and collections ". Indicates the aggregated interface.

Iterator Interface

The iterator interface executes an increasing number of elements, and provides functions similar to cyclic variables. Indicates the interface for increasing, decreasing, and traversing.

Book class

Book indicates a book, mainly used to obtain details of the book.

Bookshelf class

Bookshelf indicates the bookshelves. This class implements the aggregate interface and uses it as aggregation.

Bookshelfiterator class

Bookshelfiterator indicates the class used to scan bookshelves and implements the iterator interface function.

Main class

Used to display and test the code written above

-----------------------------------------

Code implementation: aggregate interface (aggregation abstract class)

  

/**
* Abstract the interface method to be traversed
*/
Public abstract interface aggregate {
Public abstract iterator createdeciterator ();
Public abstract iterator createinciterator ();
}

 

Iterator interface (iterator abstract class)

 


Public abstract class iterator {
Public abstract object first ();
Public Abstract Boolean hasnext ();
Public abstract object next ();
Public abstract object currentitem ();
}

Book class

/**
* Indicates the book class.
*
*/
Public class book {

Private string name = "";
Public book (string name ){
This. Name = Name;
}

Public String getname (){
Return this. Name;
}
}

 

Bookshelf class (aggregation implementation class) Import java. util. arraylist;
Import java. util. List;

Public class bookshelf implements aggregate {

Private list <Object> mbooklist;

Public bookshelf (){
Mbooklist = new arraylist <Object> ();
}

@ Override
Public iterator createdeciterator (){
Return new bookshelfiteratordec (this );
}

@ Override
Public iterator createinciterator (){
Return new bookshelfiteratorinc (this );
}

Public bookshelf addbook (Book ){
Mbooklist. Add (book );
Return this;
}

Public list <Object> getitems (){
Return mbooklist;
}

}

  BookshelfImplementedAggregateInterface, this method is generated and returnsCreatedeciterator, createinciteratorClass object instance, that is, when we send a command to scan the shelf, the "aggregation" will be returned.

 

Bookshelfiteratordec class (Implementation iterator class) public class bookshelfiteratordec extends iterator {

Private bookshelf mbookshelf;
Private int mcurrent;

Public bookshelfiteratordec (bookshelf ){
This. mbookshelf = bookshelf;
This. mcurrent = bookshelf. getitems (). Size ();
}

@ Override
Public object first (){
Return mbookshelf. getitems (). Get (mbookshelf. getitems (). Size ()-1 );
}

@ Override
Public object next () {// get the next object of the aggregation
Object ref = NULL;
Mcurrent --;
If (mcurrent> = 0 ){
Ref = mbookshelf. getitems (). Get (mcurrent );
}
Return ref;
}

@ Override
Public object currentitem (){
Return mbookshelf. getitems (). Get (mcurrent );
}

@ Override
Public Boolean hasnext (){
Return mcurrent <1? False: true;
}

}

Bookshelfiteratorinc class (Implementation iterator class)
public class BookShelfIteratorInc extends Iterator {private BookShelf mBookShelf;private int mCurrent;public BookShelfIteratorInc(BookShelf bookShelf) {this.mBookShelf = bookShelf;this.mCurrent = -1; }@Overridepublic Object first() {return mBookShelf.getItems().get(0);}@Overridepublic Object next() {        Object ref = null;          mCurrent++;          if(mCurrent<mBookShelf.getItems().size()){              ref = mBookShelf.getItems().get(mCurrent);          }          return ref;  }@Overridepublic Object currentItem() {        return mBookShelf.getItems().get(mCurrent);  }@Overridepublic boolean hasNext() {        return mCurrent < mBookShelf.getItems().size() -1 ? true : false;  }}

Main class

 

Public class main {

Public static void main (string [] ARGs ){

Bookshelf bookshelf = new bookshelf ();
Bookshelf. addbook (New Book ("android "))
. Addbook (New Book ("WP "))
. Addbook (New Book ("iOS "));

Iterator deciterator = bookshelf. createdeciterator ();

System. Out. println ("START sequential traversal ");
While (deciterator. hasnext ()){
Deciterator. Next ();
System. Out. println ("book name is:" + (book) deciterator. currentitem (). getname ());
}

Iterator inciterator = bookshelf. createinciterator ();
System. Out. println ("START reverse traversal ");
While (inciterator. hasnext ()){
Inciterator. Next ();
System. Out. println ("book name is:" + (book) inciterator. currentitem (). getname ());
}
}
}

 

The preceding execution result:

Start sequential Traversal
Book name is: IOS
Book name is: WP
Book name is: Android
Start reverse Traversal
Book name is: Android
Book name is: WP
Book name is: IOS

More function extensions

The ascending and descending traversal methods are described above. You can also add other traversal methods by yourself, such:

  • Bidirectional traversal after and after (next, previous ......)
  • Specify a subscript to get it immediately
  • And so on.
Reference: http://www.cnblogs.com/TerryBlog/archive/2011/07/05/2098666.html
Http://clq9761.iteye.com/blog/1090186
Related Article

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.