量变引发质变,论循环条件判断中次数变化引发的函数变化的处理,比较面向过程编程和面向对象编程

从一个经典迭代器案例入手

写程序模拟行车记录仪的存储和遍历视频的过程

存储原理一览

迭代器存储原理图
迭代器存储原理图2
迭代器存储原理图3
迭代器存储原理图4

遍历原理一览

迭代器迭代原理图
迭代器迭代原理图2
迭代器迭代原理图3

面向过程编程方式

代码原理图

存入数组方法原理图
面向过程之存储方法代码原理图
迭代数组方法原理图
面向过程之迭代方法代码原理图

代码结构图

面向过程之代码结构图

源码

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]);
		}
	}

}
posted on 2026-05-20 09:27  技术小伙伴  阅读(1)  评论(0)    收藏  举报