迭代器模式---学习笔记


       项目组最近接到一个项目,一个手机专卖店网店。小明,小华,小红是项目组成员,因为没有沟通好,程序员小明用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("三星手机");
	}
	
	
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值