量变引发质变,论循环条件判断中次数变化引发的函数变化的处理,比较面向过程编程和面向对象编程
从一个经典迭代器案例入手
写程序模拟行车记录仪的存储和遍历视频的过程
存储原理一览




遍历原理一览



面向过程编程方式
代码原理图
存入数组方法原理图

迭代数组方法原理图

代码结构图

源码
MyIterator
public interface MyIterator {
void save(int e);
void iterate();
}
MyIteratorImpl
public class MyIteratorImpl implements MyIterator {
private Integer[] store = new Integer[10];
private int index;
private boolean fillMark = false;
@Override
public void save(int e) {
if(index == store.length) {
index = 0;
fillMark = true;
System.out.println("this.fillMark="+fillMark);
}
store[index++] = e;
}
@Override
public void iterate() {
if(this.fillMark) {
int loopCount = store.length;
for(int i = index-1;loopCount>0;i=i==0?store.length-1:i-1,loopCount--) {
System.out.println("store["+i+"]="+store[i]);
}
} else {
for(int i = index-1;i>=0;i--) {
System.out.println("store["+i+"]="+store[i]);
}
}
}
}
面向对象编程方式
代码原理图
存入数组方法原理图

迭代数组方法原理图

代码结构图

源码
MyIterator
public interface MyIterator {
MyIterator save(int e);
void iterate();
}
AbsMyIterator
public abstract class AbsMyIterator implements MyIterator {
protected int[] store = new int[10];
protected int index;
}
NotFullImpl
public class NotFullImpl extends AbsMyIterator {
FullImpl fi = new FullImpl();
@Override
public MyIterator save(int e) {
if(this.index == this.store.length) {
index = 0;
store[index++] = e;
fi.setIndex(index);
fi.setStore(store);
return fi;
}
store[index++] = e;
return this;
}
@Override
public void iterate() {
for (int i = index - 1; i >= 0; i--) {
System.out.println("store["+i+"]="+store[i]);
}
}
}
FullImpl
public class FullImpl extends AbsMyIterator {
/*
public FullImpl(int[] store,int index) {
this.store = store;
this.index = index;
}
*/
public void setStore(int[] store) {
this.store = store;
}
public void setIndex(int index) {
this.index = index;
}
@Override
public MyIterator save(int e) {
System.out.println("fullImpl.index="+index);
if(this.index == this.store.length)
index = 0;
store[index++] = e;
return this;
}
@Override
public void iterate() {
for (int i = index - 1,loopCount = store.length; loopCount > 0; i=(i == 0)?store.length-1:--i,loopCount--) {
System.out.println("store["+i+"]="+store[i]);
}
}
}
浙公网安备 33010602011771号