Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

迭代器模式 #222

Open
louzhedong opened this issue Jun 22, 2020 · 0 comments
Open

迭代器模式 #222

louzhedong opened this issue Jun 22, 2020 · 0 comments

Comments

@louzhedong
Copy link
Owner

迭代器模式

它提供一种方法访问一个容器对象中各个元素,而又不需暴露该对象的内部细节

应用很广

到处都有它的身影

实现
Java
/**
 * 迭代器接口
 **/
public interface Iterator {
    Object next();
    boolean hasNext();
    boolean remove();
}

/**
 * 具体接口类
 **/
public class ConcreteIterator implements Iterator{
    private Vector vector = new Vector();
    public int cursor = 0;

    public ConcreteIterator(Vector _vector) {
        this.vector = _vector;
    }

    @Override
    public Object next() {
        Object result;
        if (this.hasNext()) {
            result = this.vector.get(this.cursor++);
        } else {
            result = null;
        }
        return result;
    }

    @Override
    public boolean hasNext() {
        if (this.cursor == this.vector.size()) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public boolean remove() {
        this.vector.remove(this.cursor);
        return true;
    }
}

/**
 * 抽象容器类
 **/
public interface Aggregate {
    void add(Object object);
    Iterator iterator();
}

/**
 * 具体容器类
 **/
public class ConcreteAggregate implements Aggregate{
    private Vector vector = new Vector();
    @Override
    public void add(Object object) {
        this.vector.add(object);
    }

    @Override
    public Iterator iterator() {
        return new ConcreteIterator(this.vector);
    }
}

/**
 * 场景类
 **/
public class Client {
    public static void main(String[] args) {
        Aggregate aggregate = new ConcreteAggregate();
        aggregate.add("a");
        aggregate.add("b");
        aggregate.add("c");

        Iterator iterator = aggregate.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
JavaScript
var each = function (array, callback) {
  for (var i = 0, l = array.length; i < l; i++) {
    callback.call(array[i], i, array[i]);
  }
}

each([1, 2, 3], function (i, n) {
  console.log([i, n]);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant