属于行为型模式(共11种)

    数据结构
    物理结构上做存储的只有两种结构
    连续存 array 用数组做存储
    不连续 链表做存储 指针下一个数据

    类图:
    image.png

    自定义的容器实现 一个自定义接口(collection)
    接口中有 添加 删除 容器大小等方法
    最重要的是 聚合自定义的 迭代器接口 并有一个迭代方法
    自定义接口 可以通过 内部类的方式 实现迭代器接口 重写适用于自定义容易
    遍历的 hasNext(); next();方法

    部分代码举例

    1. public interface Iterator_<E> { //Element //Type //K //Value V Tank
    2. boolean hasNext();
    3. E next(); //Tank next() Iterator_<Tank> it = ... Tank t = it.next();
    4. }
    1. public interface Collection_<E> {
    2. void add(E o);
    3. int size();
    4. Iterator_ iterator();
    5. }
    1. /**
    2. * 考虑边界问题
    3. */
    4. class ArrayList_<E> implements Collection_<E> {
    5. E[] objects = (E[])new Object[10];
    6. //objects中下一个空的位置在哪儿,或者说,目前容器中有多少个元素
    7. private int index = 0;
    8. public void add(E o) {
    9. if(index == objects.length) {
    10. E[] newObjects = (E[])new Object[objects.length*2];
    11. System.arraycopy(objects, 0, newObjects, 0, objects.length);
    12. objects = newObjects;
    13. }
    14. objects[index] = o;
    15. index ++;
    16. }
    17. public int size() {
    18. return index;
    19. }
    20. @Override
    21. public Iterator_<E> iterator() {
    22. return new ArrayListIterator();
    23. }
    24. private class ArrayListIterator<E> implements Iterator_<E> {
    25. private int currentIndex = 0;
    26. @Override
    27. public boolean hasNext() {
    28. if(currentIndex >= index) return false;
    29. return true;
    30. }
    31. @Override
    32. public E next() {
    33. E o = (E)objects[currentIndex];
    34. currentIndex ++;
    35. return o;
    36. }
    37. }
    38. }
    1. public class Main {
    2. public static void main(String[] args) {
    3. Collection_<String> list = new ArrayList_<>();
    4. for(int i=0; i<15; i++) {
    5. list.add(new String("s" + i));
    6. }
    7. System.out.println(list.size());
    8. //这个接口的调用方式:
    9. Iterator_<String> it = list.iterator();
    10. while(it.hasNext()) {
    11. String o = it.next();
    12. System.out.println(o);
    13. }
    14. }
    15. }

    链表指针实现

    1. /**
    2. * 相比数组,这个容器不用考虑边界问题,可以动态扩展
    3. */
    4. class LinkedList_ implements Collection_ {
    5. Node head = null;
    6. Node tail = null;
    7. //目前容器中有多少个元素
    8. private int size = 0;
    9. public void add(Object o) {
    10. Node n = new Node(o);
    11. n.next = null;
    12. if(head == null) {
    13. head = n;
    14. tail = n;
    15. }
    16. tail.next = n;
    17. tail = n;
    18. size++;
    19. }
    20. private class Node {
    21. private Object o;
    22. Node next;
    23. public Node(Object o) {
    24. this.o = o;
    25. }
    26. }
    27. public int size() {
    28. return size;
    29. }
    30. @Override
    31. public Iterator_ iterator() {
    32. return null;
    33. }
    34. }