Category: "java"2013-07-15 10:58 917 people read reviews (0) favorite reports The so-called iterator mode, that is, iterator provides a unified access for different containers. In this paper, we use the container in Java as an example to simulate the principle of iterator.
Reference: Horse soldier java design mode Iterator
1. First define a container collection interface.
[Java]View Plaincopy
- Package com.njupt.zhb.learn.iterator;
- Public interface Collection {
- void Add (Object o);
- int size ();
- Iterator Iterator ();
- }
2. Define an interface for an iterator iterator
[Java]View Plaincopy
- Package com.njupt.zhb.learn.iterator;
- Public interface Iterator {
- Object next ();
- boolean hasnext ();
- }
3. Define a ArrayList, implement the collection interface, and write an inner class that implements the iterator interface.
[Java]View Plaincopy
- Package com.njupt.zhb.learn.iterator;
- Import com.njupt.zhb.learn.iterator.Collection;
- Public class ArrayList implements Collection {
- Object[] objects = new object[10];
- int index = 0;
- public Void Add (Object o) {
- if (index = = objects.length) {
- object[] newobjects = new Object[objects.length * 2];
- System.arraycopy (objects, 0, Newobjects, 0, objects.length);
- objects = newobjects;
- }
- Objects[index] = o;
- Index + +;
- }
- public int size () {
- return index;
- }
- Public Iterator Iterator () {
- return new Arraylistiterator ();
- }
- private class Arraylistiterator implements Iterator {
- private int currentindex = 0;
- @Override
- Public Boolean hasnext () {
- if (currentindex >= index) return false;
- Else return true;
- }
- @Override
- Public Object Next () {
- Object o = Objects[currentindex];
- Currentindex + +;
- return o;
- }
- }
- }
4. Write the test procedure Testmain
[Java]View Plaincopy
- Package com.njupt.zhb.learn.iterator;
- Import com.njupt.zhb.learn.iterator.ArrayList;
- Public class Testmain {
- public static void Main (string[] args) {
- Collection C = new ArrayList ();
- For (int i=0; i<; i++) {
- C.add ("string" +i);
- }
- System.out.println (C.size ());
- Iterator it = C.iterator ();
- While (It.hasnext ()) {
- Object o = It.next ();
- System.out.println (o.tostring () + "");
- }
- }
- }
Operation Result:
[HTML]View Plaincopy
- 15
- String 0
- String 1
- String 2
- String 3
- String 4
- String 5
- String 6
- String 7
- String 8
- String 9
- String 10
- String 11
- String 12
- String 13
- String 14
As can be seen from the above, design patterns are used everywhere in object-oriented
polymorphic。
interface calls a function in a subclass。 Source code Download:
http://download.csdn.net/detail/nuptboyzhb/5755295
Iterator mode of Java design pattern