?? 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 + -