1. package sample.design_pattern;
  2.  
  3. interface Iterator {
  4. public abstract boolean hasNext();
  5. public abstract void next();
  6.  
  7. public abstract Object getValue();
  8. }
  9.  
  10.  
  11.  
  12. interface Aggregate {
  13. public abstract Iterator iterator();
  14. }
  15.  
  16.  
  17.  
  18. class Element {
  19. private int value;
  20.  
  21. public Element(int value) {
  22. this.value = value;
  23. }
  24.  
  25. public int getValue() {
  26. return value;
  27. }
  28.  
  29. public void setValue(int value) {
  30. this.value = value;
  31. }
  32. }
  33.  
  34.  
  35.  
  36. class ElementIterator implements Iterator {
  37. private ElementList list;
  38. private int index;
  39.  
  40. public ElementIterator(ElementList list) {
  41. this.list = list;
  42. this.index = 0;
  43. }
  44.  
  45. public boolean hasNext() {
  46. return (list.getLastNum() > index) ? true : false;
  47. }
  48.  
  49. public void next() {
  50. ++index;
  51. }
  52.  
  53. public Object getValue() {
  54. return list.getValueAt(index);
  55. }
  56. }
  57.  
  58.  
  59.  
  60. class ElementList implements Aggregate {
  61. private Element[] list;
  62. private int last = 0;
  63.  
  64. public ElementList(int count) {
  65. this.list = new Element[count];
  66. }
  67.  
  68. public void add(Element element) {
  69. list[last++] = element;
  70. }
  71.  
  72. public Element getValueAt(int index) {
  73. return list[index];
  74. }
  75.  
  76. public int getLastNum() {
  77. return last;
  78. }
  79.  
  80. public Iterator iterator() {
  81. return new ElementIterator(this);
  82. }
  83. }
  84.  
  85.  
  86.  
  87. public class IteratorPatternTest {
  88. public static void main(String[] args) {
  89. ElementList list = new ElementList(5);
  90.  
  91. for (int i = 0; i < 5; ++i) {
  92. list.add(new Element(i));
  93. }
  94.  
  95. for (Iterator it = list.iterator(); it.hasNext(); it.next()) {
  96. System.out.println(((Element)it.getValue()).getValue());
  97. }
  98. }
  99. }
  100.  

タグ:

DesignPattern Java
最終更新:2008年09月09日 19:45