JavaJava设计模式

设计模式-迭代器模式

2019-05-09  本文已影响6人  smallmartial

1.迭代器模式介绍

迭代器模式:提供一种方法顺序的访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。

2.迭代器模式角色构成

3.示例

image.png

定义迭代器角色(Iterator)

public interface MyIterator
{
    public boolean hasmore();
    public Object next();
}

定义具体迭代器角色(Concrete Iterator)

public class MyClassIterator implements MyIterator 
{
    private Aggregate myClass;
    private Student[] students;
    private int pointer;
    public MyClassIterator(Aggregate myClass)
    {
        students = ((MyClass)myClass).getDatas();
        this.myClass = myClass; 
        pointer = 0;
    }
    public boolean hasmore()
    {
        if (pointer < ((MyClass)myClass).size() && students[pointer] != null)
            return true;
        else
            return false;
    }
    public Object next()
    {       
        Object o = null;
        if (hasmore())
        {
            o = students[pointer];
            pointer++;
        }
        return o;
    }

}

定义容器角色(Aggregate)

public interface Aggregate  
{
    public MyIterator getIterator();
}

定义具体容器角色(ConcreteAggregate)

public class MyClass implements Aggregate
{
    private Student[] students;
    private final int SIZE = 40; 
    private int currentPos;
    public MyClass()
    {
        students = new Student[SIZE];
        currentPos = 0;
    }
    public Student[] getDatas()
    {
        return students;
    }
    public int size()
    {
        return SIZE;
    }
    public MyIterator getIterator()
    {
        MyIterator  iterator = new MyClassIterator(this);
        return iterator;
    }
    public void add(Student student)
    {
        if (currentPos == SIZE -1)
        {
            System.out.println("班级满额,不能再添加学生!");
        }
        else
        {
            students[currentPos++] = student;
        }
    }
}

Student类

public class Student
{
    private String name;
    public Student(String name)
    {
        this.name = name;
    }
    public String toString()
    {
        return name;
    }
}

代码测试

public class Application
{
    public static void main(String[] args) 
    {
        Aggregate aClass = new MyClass();
        ((MyClass)aClass).add(new Student("张三"));
        ((MyClass)aClass).add(new Student("李四"));
        ((MyClass)aClass).add(new Student("王五"));
        ((MyClass)aClass).add(new Student("赵六"));

        MyIterator iterator = aClass.getIterator();
        
        while (iterator.hasmore())
            System.out.println((Student)iterator.next());

    }
}

4.总结

迭代器模式的优点:

迭代器模式的缺点:

总的来说: 迭代器模式是与集合共生共死的,一般来说,我们只要实现一个集合,就需要同时提供这个集合的迭代器,就像java中的Collection,List、Set、Map等,这些集合都有自己的迭代器。假如我们要实现一个这样的新的容器,当然也需要引入迭代器模式,给我们的容器实现一个迭代器。

上一篇 下一篇

猜你喜欢

热点阅读