//
//
// Generated by StarUML(tm) Java Add-In
//
// @ Project : Untitled
// @ File Name : State.java
// @ Date : 2016/8/30
// @ Author :
//
//
public interface State {
public void onEnterState();
public void observe();
}
//
//
// Generated by StarUML(tm) Java Add-In
//
// @ Project : Untitled
// @ File Name : PeacefulState.java
// @ Date : 2016/8/30
// @ Author :
//
//
public class PeacefulState implements State {
private Mammoth mammoth;
public PeacefulState(Mammoth mammoth) {
this.mammoth = mammoth;
}
public void onEnterState() {
System.out.println(String.format("%s calms down.", mammoth));
}
public void observe() {
System.out.println(String.format("%s is calm and peaceful.", mammoth));
}
}
//
//
// Generated by StarUML(tm) Java Add-In
//
// @ Project : Untitled
// @ File Name : AngryState.java
// @ Date : 2016/8/30
// @ Author :
//
//
public class AngryState implements State {
private Mammoth mammoth;
public AngryState(Mammoth mammoth) {
this.mammoth = mammoth;
}
public void onEnterState() {
System.out.println(String.format("%s gets angry!", mammoth));
}
public void observe() {
System.out.println(String.format("%s is furious!", mammoth));
}
}
//
//
// Generated by StarUML(tm) Java Add-In
//
// @ Project : Untitled
// @ File Name : Mammoth.java
// @ Date : 2016/8/30
// @ Author :
//
//
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();
}
public String toString() {
return "The mammoth";
}
public void observe() {
this.state.observe();
}
}
public class App {
public static void main(String[] args) {
Mammoth mammoth = new Mammoth();
mammoth.observe();
mammoth.timePasses();
mammoth.observe();
mammoth.timePasses();
mammoth.observe();
}
}
/*The mammoth is calm and peaceful.
The mammoth gets angry!
The mammoth is furious!
The mammoth calms down.
The mammoth is calm and peaceful.
*/
java设计模式进阶_state
最新推荐文章于 2019-01-23 19:58:06 发布