Last active
March 5, 2020 06:24
-
-
Save vgheo/5f05585de62bdc12bfe4e7fa2f962963 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class IteratorResultSetAdapter<T> implements Iterator<T> { | |
private final ResultSet rs; | |
private final State INIT=new Init(); | |
private final State LOADED=new Loaded(); | |
private final State END=new End(); | |
private State state; | |
private T currentValue=null; | |
private boolean currentValid=false; | |
public IteratorResultSetAdapter(rs) { | |
this.rs=rs; | |
enter(INIT); | |
} | |
boolean hasNext() { | |
return state.hasNext(); | |
} | |
T next() { | |
return state.next(); | |
} | |
void enter(State s) default { | |
state=s; | |
s.onEntry(); | |
} | |
private interface State { | |
boolean hasNext(); | |
T next(); | |
void onEntry() default {} | |
} | |
private class Init implements State { | |
void onEntry() { | |
currentElement=null; | |
} | |
boolean hasNext() { | |
if(rs.next()) { | |
currentElement=map(rs); | |
enter(LOADED); | |
return true; | |
} else { | |
enter(END); | |
return false; | |
} | |
} | |
T next() { | |
if(rs.next()) { | |
// remain in INIT; | |
return map(rs); | |
} else { | |
enter(END); | |
throw new NoSuchElementException(); | |
} | |
} | |
class Loaded implements State { | |
boolean hasNext() { | |
return true; | |
} | |
T next() { | |
val res=currentElement; | |
enter(INIT); | |
return res; | |
} | |
} | |
class End implements State { | |
boolean hasNext() { | |
return false; | |
} | |
T next() { | |
throw new NoSuchElementException(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment