public interface State {
void onEnterState();
void observe();
}
public class PeacefulState implements State {
private static final Logger LOGGER = LoggerFactory.getLogger(PeacefulState.class);
private Mammoth mammoth;
public PeacefulState(Mammoth mammoth) { this.mammoth = mammoth; }
@Override public void observe() { LOGGER.info("{} is calm and peaceful.", mammoth); }
@Override public void onEnterState() { LOGGER.info("{} calms down.", mammoth); }
}
public class AngryState implements State {
private static final Logger LOGGER = LoggerFactory.getLogger(AngryState.class);
private Mammoth mammoth;
public AngryState(Mammoth mammoth) { this.mammoth = mammoth; }
@Override public void observe() { LOGGER.info("{} is furious!", mammoth); }
@Override public void onEnterState() { LOGGER.info("{} gets angry!", mammoth); }
}
public class Mammoth {
private State state;
public Mammoth() { state = new PeacefulState(this); }
public void timePasses() { if (state.getClass().equals(PeacefulState.class)) { changeStateTo(new AngryState(this)); } else { changeStateTo(new PeacefulState(this)); } }
private void changeStateTo(State newState) { this.state = newState; this.state.onEnterState(); }
@Override public String toString() { return "The mammoth"; }
public void observe() { this.state.observe(); } }
public class App {
public static void main(String[] args) {
var mammoth = new Mammoth(); mammoth.observe(); mammoth.timePasses(); mammoth.observe(); mammoth.timePasses(); mammoth.observe();
} }
|