项目组最近接到一个项目,一个手机专卖店网店。小明,小华,小红是项目组成员,因为没有沟通好,程序员小明用Set集合存储手机数据,而程序员小华用List集合存储手机数据,小红用数组来存储手机数据......店面的手机数据需要从集合中取,现在问题来了,没有通用的方法可以从存储对象中获取手机数据。Set,List,数组中的手机数据都要分别遍历,小明了解迭代器,就建议用集合Set,List自带的获取迭代器Iterator就可以了,但是还有一个数组......其实方案已经出来了,让这个存储手机数据的对象数组继承Iterator接口,分别实现hasNext(),next(),remove()方法问题就解决了,这也就是迭代器模式。看下来的类图以及代码:
实现Iterator的SamSungIterator
public class SamSungIterator implements Iterator{
MobilePhone[] samSungs;
int position = 0;
public SamSungIterator(MobilePhone[] samSungs){
this.samSungs = samSungs;
}
@Override
public Object next() {
MobilePhone mobilePhone = samSungs[position];
position = position + 1;
return mobilePhone;
}
@Override
public boolean hasNext() {
if(position >= samSungs.length || samSungs[position] ==null ){
return false;
}else{
return true;
}
}
@Override
public void remove() {
// TODO Auto-generated method stub
}
}
public interface MobilePhones {
public Iterator createIterator();
}
public class SamSungs implements MobilePhones{
MobilePhone[] samSungs;
public SamSungs(){
this.samSungs = new MobilePhone[3];
samSungs[0] = new SamSung();
samSungs[1] = new SamSung();
samSungs[2] = new SamSung();
}
@Override
public Iterator createIterator() {
return new SamSungIterator(samSungs);
}
}
import java.util.Iterator;
public class MobilePhone {
private String name;
private String color;
private Integer price;
public void printMobileInfo(){
}
}
public class SamSung extends MobilePhone{
private String name;
private String color;
private Integer price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public void printMobileInfo(){
System.out.println("三星手机");
}
}