Design Pattern-iterators

Source: Internet
Author: User

Definition: Provides a way to sequentially access individual elements in an aggregated object without exposing their internal representations.

UML Class Diagrams:

1 InterfaceIterator {2      PublicObject Next ();3      Public BooleanHasnext ();4 }5 classConcreteiteratorImplementsiterator{6     PrivateList List =NewArrayList ();7     Private intCursor =0;8      Publicconcreteiterator (List list) {9          This. List =list;Ten     } One      Public BooleanHasnext () { A         if(cursor==list.size ()) { -             return false; -         } the         return true; -     } -      PublicObject Next () { -Object obj =NULL; +         if( This. Hasnext ()) { -obj = This. List.get (cursor++); +         } A         returnobj; at     } - } - InterfaceAggregate { -      Public voidAdd (Object obj); -      Public voidRemove (Object obj); -      PublicIterator Iterator (); in } - classConcreteaggregateImplementsAggregate { to     PrivateList List =NewArrayList (); +      Public voidAdd (Object obj) { - list.add (obj); the     } *   $      PublicIterator Iterator () {Panax Notoginseng         return Newconcreteiterator (list); -     } the   +      Public voidRemove (Object obj) { A list.remove (obj); the     } + } -  Public classClient { $      Public Static voidMain (string[] args) { $Aggregate AG =Newconcreteaggregate (); -Ag.add ("Xiao Ming"); -Ag.add ("Little Red"); theAg.add ("Xiao Gang")); -Iterator it =ag.iterator ();Wuyi          while(It.hasnext ()) { theString str =(String) It.next (); - System.out.println (str); Wu         } -     } About}

Design Pattern-iterators

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.