功能:
过程:
- 定义接口Selector(end(),current(),next())
- 类Sequence
通过构造函数定义,Object数组大小
定义添加Object方法
私有内部类SequenceSelector 实现Selector
定义生产SequenceSelector方法Selector
主方法:定义一个10元素的Sequence,运用Selector输出
个人实现:
package thinking;
interface Selector{
Boolean end();//different-boolean
Object current();
void next();
}
public class Sequence {
int i=0;//different-private
Object[] intems;
public Sequence(int size) {
intems = new Object[size];
}
public void add(Object obj){
if(i<intems.length){
intems[i++] = obj;
}
}
//different
private class SequenceSelector implements Selector{
@Override
public Boolean end() {
if(i==0){
return true;
}else{
return false;
}
}
@Override
public Object current() {
// TODO Auto-generated method stub
return intems[intems.length-i];
}
@Override
public void next() {
// TODO Auto-generated method stub
i--;//different-未加判定
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Sequence sequence = new Sequence(10);
for(int i=0;i<10;i++){
sequence.add(i);
}
//different
SequenceSelector sequenceSelector = sequence.new SequenceSelector();
while (!sequenceSelector.end()) {
System.out.println(sequenceSelector.current());
sequenceSelector.next();
}
}
}
原书实现:
package thinkingjava;
interface Selector{
boolean end();
Object current();
void next();
}
public class Sequence {
private int next=0;
private Object[] items;
public Sequence(int size) {
items = new Object[size];
}
public void add(Object obj){
if(next<items.length){
items[next++] = obj;
}
}
private class SequenceSelector implements Selector{
private int i = 0;
@Override
public boolean end() {
return i==items.length;
}
@Override
public Object current() {
// TODO Auto-generated method stub
return items[i];
}
@Override
public void next() {
// TODO Auto-generated method stub
if(i<items.length)
i++;
}
}
public Selector selector() {
return new SequenceSelector();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Sequence sequence = new Sequence(10);
for(int i=0;i<10;i++){
sequence.add(i);
}
Selector selector = sequence.selector();
while (!selector.end()) {
System.out.print(selector.current()+" ");
selector.next();
}
}
}
不同:见个人实现注释