📄 client.java
字号:
/*
* Created on 2005-5-11
*
意图 提供一种方法顺序访问一个聚合对象中各个元素, 而又不需暴露该对象的内部表示。
适用性 访问一个聚合对象的内容而无需暴露它的内部表示。
支持对聚合对象的多种遍历。
为遍历不同的聚合结构提供一个统一的接口(即, 支持多态迭代)。
*/
package com.test.pattern.behavir.iterator;
import java.util.ArrayList;
/**
* @author Administrator
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
class Node {
private String name;
public String getName() {
return name;
}
public Node(String s) {
name = s;
}
}
class NodeCollection {
private ArrayList list = new ArrayList();
private int nodeMax = 0;
// left as a student exercise - implement collection
// functions to remove and edit entries also
public void AddNode(Node n) {
list.add(n);
nodeMax++;
}
public Node GetNode(int i) {
return ((Node) list.get(i));
}
public int getNodeMax() {
return nodeMax;
}
}
/*
* The iterator needs to understand how to traverse the collection It can do
* that as way it pleases - forward, reverse, depth-first,
*/
abstract class Iterator {
abstract public Node Next();
}
class ReverseIterator extends Iterator {
private NodeCollection nodeCollection;
private int currentIndex;
public ReverseIterator(NodeCollection c) {
nodeCollection = c;
currentIndex = c.getNodeMax() - 1; // array index starts at 0!
}
// note: as the code stands, if the collection changes,
// the iterator needs to be restarted
public Node Next() {
if (currentIndex == -1)
return null;
else
return (nodeCollection.GetNode(currentIndex--));
}
}
/// <summary>
/// Summary description for Client.
/// </summary>
public class Client {
public static void main(String[] args) {
NodeCollection c = new NodeCollection();
c.AddNode(new Node("first"));
c.AddNode(new Node("second"));
c.AddNode(new Node("third"));
// now use iterator to traverse this
ReverseIterator i = new ReverseIterator(c);
// the code below will work with any iterator type
Node n;
do {
n = i.Next();
if (n != null)
System.out.println(n.getName());
} while (n != null);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -