设计模式之迭代器模式java实现代码
迭代器模式:提供一个方法顺序访问一个聚合对象中的各个元素,而又不暴露其内部的表示。
迭代器模式提供了一种方法,可以顺序访问一个聚合对象中的元素,而又不用知道内部是如何标示的。另外,迭代器模式把在元素之间游走的责任交给迭代器,而不是聚合对象,让聚合更专注于数据集合。
案例实现情景:我和友人去超市分头购物,在结帐时,我们遍历一下我们的 “扫货” 清单(遍历打印购物清单),在实现上,Me使用ArrayList,友人使用Thing[]数组,给遍历造成困扰。
案例代码:
Thing.java
public class Thing { private String name; private long price; public Thing(String name,long price){ this.name = name; this.price = price; } @Override public String toString() { return "Thing [name=" + name + ", price=" + price + "]"; } }
Me.java
import java.util.ArrayList; import java.util.Iterator; public class Me { private ArrayList<Thing> shopping = new ArrayList<Thing>(); public Me(){ shopping.add(new Thing("巧克力", 35)); shopping.add(new Thing("凉茶", 4)); shopping.add(new Thing("袜子", 9)); shopping.add(new Thing("香蕉", 12)); } public Iterator<Thing> createIterator(){ return shopping.iterator(); } }
Friends.java
import java.util.Iterator; public class Friends { private Thing[] shopping = new Thing[100]; public Friends(){ shopping[0] = new Thing("牛奶",15); shopping[1] = new Thing("苹果",10); shopping[2] = new Thing("薯片",4); } public Iterator<Thing> createIterator(){ return new ArrayIterator(shopping); } }
ArrayIterator.java
import java.util.Iterator; public class ArrayIterator implements Iterator<Thing>{ private Thing[] thingArray; private int position = 0; public ArrayIterator(Thing[] array){ thingArray = array; } @Override public boolean hasNext() { while(position<thingArray.length && thingArray[position] != null){ return true; } return false; } @Override public Thing next() { return thingArray[position++]; } @Override public void remove() { //noting to do } }
Test.java
import java.security.AllPermission; import java.util.ArrayList; import java.util.Iterator; public class Test { public static void main(String args[]){ ArrayList<Iterator<Thing>> allIterator = new ArrayList<Iterator<Thing>>(); Me me = new Me(); Friends friends = new Friends(); Iterator<Thing> meIterator = me.createIterator(); Iterator<Thing> friendsIterator = friends.createIterator(); allIterator.add(meIterator); allIterator.add(friendsIterator); for(Iterator<Thing> iterator:allIterator){ while(iterator.hasNext()){ System.out.println(iterator.next()); } System.out.println("---------------------"); } } }
测试结果:
Thing [name=巧克力, price=35] Thing [name=凉茶, price=4] Thing [name=袜子, price=9] Thing [name=香蕉, price=12] --------------------- Thing [name=牛奶, price=15] Thing [name=苹果, price=10] Thing [name=薯片, price=4] ---------------------
总结:
设计原则:
单一职责:一个类应该只有一个引起变化的职责。
当一个模块或一个类被设计成只支持一组相关的功能时,我们说它具有高内聚。