State: internal state object defines current behavior. The state changes, the behavior changes. Thay vì dùng if else bên ngoài, ta dùng state bên trong.
[code lang=”java”] public static void main(String[] args) {Birth birth = new Birth();
}
public class Birth {
private State state; // interface
public Birth() {
state = new HappyState(this);
}
/**
* Makes time pass for the mammoth
*/
public void timePasses() {
if (state.getClass().equals(HappyState.class)) {
changeStateTo(new AngryState(this));
} else {
changeStateTo(new HappyState(this));
}
}
private void changeStateTo(State newState) {
this.state = ...
AUG
2016