概念:提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示
    应用:java的foreach
    image.png

    java代码:

    1. public class IteratorTest {
    2. public static void main(String[] args) {
    3. Aggregate aggregate = new ConcreteAggregate();
    4. aggregate.Add(new Object());
    5. aggregate.Add(new Object());
    6. Iterator iterator = aggregate.CreateIterator();
    7. while(!iterator.IsDone()){
    8. System.out.println(iterator.CurrentItem());
    9. iterator.Next();
    10. }
    11. }
    12. }
    13. //迭代器抽象类
    14. public abstract class Iterator {
    15. public abstract Object First();
    16. public abstract Object Next();
    17. public abstract boolean IsDone();
    18. public abstract Object CurrentItem();
    19. }
    20. //迭代器类
    21. public class ConcreteIterator extends Iterator {
    22. Aggregate aggregate;
    23. int current = 0;
    24. public ConcreteIterator(Aggregate aggregate) {
    25. this.aggregate = aggregate;
    26. }
    27. @Override
    28. public Object First() {
    29. return aggregate.getObject(0);
    30. }
    31. @Override
    32. public Object Next() {
    33. Object temp = aggregate.getObject(current);
    34. current++;
    35. return temp;
    36. }
    37. @Override
    38. public boolean IsDone() {
    39. if (aggregate.Count() == current) {
    40. return true;
    41. }
    42. return false;
    43. }
    44. @Override
    45. public Object CurrentItem() {
    46. return aggregate.getObject(current);
    47. }
    48. }
    49. //遍历对象抽象类
    50. public abstract class Aggregate {
    51. public abstract Iterator CreateIterator();
    52. public abstract Object getObject(int index);
    53. public abstract int Count();
    54. public abstract void Add(Object object);
    55. }
    56. //遍历对象实现类
    57. public class ConcreteAggregate extends Aggregate {
    58. List<Object> list = new ArrayList<>();
    59. @Override
    60. public Iterator CreateIterator() {
    61. return new ConcreteIterator(this);
    62. }
    63. public Object getObject(int index){
    64. return list.get(index);
    65. }
    66. @Override
    67. public int Count() {
    68. return list.size();
    69. }
    70. @Override
    71. public void Add(Object object) {
    72. list.add(object);
    73. }
    74. }