服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Java使用设计模式中迭代器模式构建项目的代码结构示例

Java使用设计模式中迭代器模式构建项目的代码结构示例

2020-04-22 11:54匆忙拥挤repeat Java教程

这篇文章主要介绍了Java使用设计模式中迭代器模式构建项目的代码结构示例,迭代器模式能够对访问者隐藏对象的内部细节,需要的朋友可以参考下

迭代器(Iterator)模式,又叫做游标(Cursor)模式。GOF给出的定义为:提供一种方法访问一个容器(container)对象中各个元素,而又不需暴露该对象的内部细节。
 
迭代器模式由以下角色组成:
迭代器角色(Iterator):迭代器角色负责定义访问和遍历元素的接口。
具体迭代器角色(Concrete Iterator):具体迭代器角色要实现迭代器接口,并要记录遍历中的当前位置。
容器角色(Container):容器角色负责提供创建具体迭代器角色的接口。
具体容器角色(Concrete Container):具体容器角色实现创建具体迭代器角色的接口。这个具体迭代器角色与该容器的结构相关。

Java实现示例
类图:

Java使用设计模式中迭代器模式构建项目的代码结构示例

代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
/**
 * 自定义集合接口, 类似java.util.Collection
 * 用于数据存储
 * @author stone
 *
 */
public interface ICollection<T> {
   
  IIterator<T> iterator(); //返回迭代器
  void add(T t);
  T get(int index);
}
?
1
2
3
4
5
6
7
8
9
10
11
12
/**
 * 自定义迭代器接口 类似于java.util.Iterator
 * 用于遍历集合类ICollection的数据
 * @author stone
 *
 */
public interface IIterator<T> {
  boolean hasNext();
  boolean hasPrevious();
  T next();
  T previous();
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
 * 集合类, 依赖于MyIterator
 * @author stone
 */
public class MyCollection<T> implements ICollection<T> {
 
  private T[] arys;
  private int index = -1;
  private int capacity = 5;
   
  public MyCollection() {
    this.arys = (T[]) new Object[capacity];
  }
   
  @Override
  public IIterator<T> iterator() {
    return new MyIterator<T>(this);
  }
   
  @Override
  public void add(T t) {
    index++;
    if (index == capacity) {
      capacity *= 2;
      this.arys = Arrays.copyOf(arys, capacity);
       
    }
    this.arys[index] = t;
  }
   
  @Override
  public T get(int index) {
    return this.arys[index];
  }
   
}

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
 * 若有新的存储结构,可new 一个ICollection, 对应的 new 一个IIterator来实现它的遍历
 */
@SuppressWarnings({"rawtypes", "unchecked"})
public class Test {
  public static void main(String[] args) {
    ICollection<Integer> collection = new MyCollection<Integer>();
    add(collection, 3, 5, 8, 12, 3, 3, 5);
    for (IIterator<Integer> iterator = collection.iterator(); iterator.hasNext();) {
      System.out.println(iterator.next());
    }
     
    System.out.println("-------------");
     
    ICollection collection2 = new MyCollection();
    add(collection2, "a", "b", "c", 3, 8, 12, 3, 5);
    for (IIterator iterator = collection2.iterator(); iterator.hasNext();) {
      System.out.println(iterator.next());
    }
     
  }
   
  static <T> void add(ICollection<T> c, T ...a) {
    for (T i : a) {
      c.add(i);
    }
  }
}

打印:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
3
5
8
12
3
3
5
-------------
a
b
c
3
8
12
3
5

 

延伸 · 阅读

精彩推荐