I recently implemented this very pattern in a web application, in which I wanted to represent the current state (in the sense of REST) in such a way that I could say
state.getNextPage().getRest()
to get the URL which represents "the next page of results".
In order to permit construction of arbitrary, unknown future subclasses, I use the factory method.
// pseudo-code
class StateWithPage implements State {
public State getNextPage() {
return createState(this.page + 1);
} protected State createState(final int page) {
return new StateWithPage(page);
}
}class StateWithPageAndColor extends StateWithPage {
protected State createState(final int page) {
return new StateWithPageAndColor(page, this.color);
}
}