Design Pattern-iterator Pattern

Source: Internet
Author: User

Design Pattern-iterator Pattern

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

Structure:


<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + yr7A/bt6wuujuw.vcd4kphbyzsbjbgfzcz0 = "brush: java;"> public interface Iterator {public Object First (); public Object Next (); public boolean isDone (); public Object currentItem ();} public class ConcreteIterator implements Iterator {private ConcreteAggregate aggregate; private int current = 0; public ConcreteIterator (ConcreteAggregate aggregate) {this. aggregate = aggregate;} @ Overridepublic Object Firs T () {// TODO Auto-generated method stubreturn aggregate. get (0) ;}@ Overridepublic Object Next () {// TODO Auto-generated method stubgObject ret = null; current ++; if (current <aggregate. count () {ret = aggregate. get (current);} return ret;} @ Overridepublic boolean isDone () {// TODO Auto-generated method stubreturn current> = aggregate. count ()? True: false;} @ Overridepublic Object currentItem () {// TODO Auto-generated method stubreturn aggregate. get (current) ;}} public abstract class Aggregate {public abstract Iterator createIterator ();} public class ConcreteAggregate extends Aggregate {private List Items = new ArrayList(); @ Overridepublic Iterator createIterator () {// TODO Auto-generated method stubreturn new ConcreteIterator (this);} public int count () {return items. size ();} public Object get (int index) {return items. get (index);} public void add (Object obj) {items. add (obj );}}The client code is as follows:

Public class Client {public static void main (String [] args) {ConcreteAggregate a = new ConcreteAggregate ();. add ("123");. add ("cainiao");. add ("Ali"); Iterator I = new ConcreteIterator (a); Object item = I. first (); while (! I. isDone () {System. out. println (I. currentItem (); I. Next ();}}}

Running result:

123

Cainiao

Alibaba



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.