假設, 各種飲料店實作, 儲存資料的方式都不同時...
public class TeaBeverage{
ArrayList allTea;
public TeaBeverage{
allTea = new ArrayList();
Item item = new Item();
item.setName("紅茶");
allTea.add(item);
item = new Item();
item.setName("奶茶");
allTea.add(item);
}
public ArrayList getAllItem(){
return allTea;
}
}
public class CafeBeverage{
ArrAllCafe[] arrAllCafe;
public CafeBeverage{
arrAllCafe = new ArrAllCafe[2];
Item item = new Item();
item.setName("紅茶");
arrAllCafe[0] = item;
item = new Item();
item.setName("奶茶");
arrAllCafe[1] = item;
}
public ArrayList getAllItem(){
return arrAllCafe;
}
}
這時, 我們若要取出tea, cafe的所有資料, 它們return的類型是不同的
所以若這二個class能針對interface實現, 我們在使用時, 也針對這interface
好處:
1.把實作的儲存方式封裝起來
2.解藕
public interface IIterator{
boolean hasNext();
Object next();
}
public class CafeBeverageIterator implements IIterator{
ArrAllCafe[] arrAllCafe;
int position = 0;
public CafeBeverageIterator(ArrAllCafe[] arrAllCafe){
this.arrAllCafe = arrAllCafe;
}
public Object next(){
Item item = arrAllCafe[position];
position = position + 1;
return item;
}
public boolean hasNext(){
if(position >= arrAllCafe.length || arrAllCafe[position] == null){
return false;
}else{
return true;
}
}
}
修改原本的CafeBeverage, 改成回傳Iterator interface
public class CafeBeverage{
//同上
//public ArrayList getAllItem(){
//return arrAllCafe;
//}
public IIterator createIterator(){
return CafeBeverageIterator(arrAllCafe);
}
}
未完
沒有留言:
張貼留言