行为型模式用于描述程序在运行时复杂的流程控制,即描述多个类或对象之间怎样相互协作共同完成单个对象都无法单独完成的任务,它涉及算法与对象间职责的分配。
行为型模式分为类行为模式和对象行为模式,前者采用继承机制来在类间分派行为,后者采用组合或聚合在对象间分配行为。由于组合关系或聚合关系比继承关系耦合度低,满足“合成复用原则”,所以对象行为模式比类行为模式具有更大的灵活性。
行为型模式分为:
模板方法模式
策略模式
命令模式
职责链模式
状态模式
观察者模式
中介者模式
迭代器模式
访问者模式
备忘录模式
解释器模式
以上 11 种行为型模式,除了模板方法模式和解释器模式是类行为型模式,其他的全部属于对象行为型模式。
提供一个对象来顺序访问聚合对象中的一系列数据,而不暴露聚合对象的内部表示。
抽象聚合(Aggregate)角色:定义存储、添加、删除聚合元素以及创建迭代器对象的接口。
具体聚合(ConcreteAggregate)角色:实现抽象聚合类,返回一个具体迭代器的实例。
抽象迭代器(Iterator)角色:定义访问和遍历聚合元素的接口,通常包含 hasNext()、next() 等方法。
具体迭代器(Concretelterator)角色:实现抽象迭代器接口中所定义的方法,完成对聚合对象的遍历,记录遍历的当前位置。
定义一个可以存储学生对象的容器对象,将遍历该容器的功能交由迭代器实现,涉及到的类如下:
定义迭代器接口,声明hasNext、next方法
public interface StudentIterator {boolean hasNext();Student next();
}
定义具体的迭代器类,重写所有的抽象方法
public class StudentIteratorImpl implements StudentIterator {private List list;private int position = 0;public StudentIteratorImpl(List list) {this.list = list;}@Overridepublic boolean hasNext() {return position < list.size();}@Overridepublic Student next() {Student currentStudent = list.get(position);position ++;return currentStudent;}
}
定义抽象容器类,包含添加元素,删除元素,获取迭代器对象的方法
public interface StudentAggregate {void addStudent(Student student);void removeStudent(Student student);StudentIterator getStudentIterator();
}
定义具体的容器类,重写所有的方法
public class StudentAggregateImpl implements StudentAggregate {private List list = new ArrayList(); // 学生列表@Overridepublic void addStudent(Student student) {this.list.add(student);}@Overridepublic void removeStudent(Student student) {this.list.remove(student);}@Overridepublic StudentIterator getStudentIterator() {return new StudentIteratorImpl(list);}
}
优点
它支持以不同的方式遍历一个聚合对象,在同一个聚合对象上可以定义多种遍历方式。在迭代器模式中只需要用一个不同的迭代器来替换原有迭代器即可改变遍历算法,我们也可以自己定义迭代器的子类以支持新的遍历方式。
迭代器简化了聚合类。由于引入了迭代器,在原有的聚合对象中不需要再自行提供数据遍历等方法,这样可以简化聚合类的设计。
在迭代器模式中,由于引入了抽象层,增加新的聚合类和迭代器类都很方便,无须修改原有代码,满足 “开闭原则” 的要求。
缺点
增加了类的个数,这在一定程度上增加了系统的复杂性。
ArrayList举例来说明
List:抽象聚合类
ArrayList:具体的聚合类
Iterator:抽象迭代器
list.iterator():返回的是实现了 Iterator 接口的具体迭代器对象
public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, java.io.Serializable {public Iterator iterator() {return new Itr();}private class Itr implements Iterator {int cursor; // 下一个要返回元素的索引int lastRet = -1; // 上一个返回元素的索引int expectedModCount = modCount;Itr() {}//判断是否还有元素public boolean hasNext() {return cursor != size;}//获取下一个元素public E next() {checkForComodification();int i = cursor;if (i >= size)throw new NoSuchElementException();Object[] elementData = ArrayList.this.elementData;if (i >= elementData.length)throw new ConcurrentModificationException();cursor = i + 1;return (E) elementData[lastRet = i];}...
}
来源:https://www.bilibili.com/video/BV1Np4y1z7BU?p=125&spm_id_from=pageDriver&vd_source=b901ef0e9ed712b24882863596eab0ca