设计模式---状态模式
以前的示例
public class Person {
private int hour;
public int getHour() {
return hour;
}
public void setHour(int hour) {
this.hour = hour;
}
public void doSomething(){
if(hour == 7) {
System.out.println("吃早餐");
} else if(hour == 12) {
System.out.println("吃中饭");
} else if(hour == 18) {
System.out.println("吃晚饭");
} else {
System.out.println(hour + "未定义");
}
}
}
public class MainClass {
public static void main(String[] args) {
Person person = new Person();
person.setHour(7);
person.doSomething();
person.setHour(12);
person.doSomething();
person.setHour(18);
person.doSomething();
person.setHour(8);
person.doSomething();
}
}
现在的示例
package com.ibeifeng.ex3;
public abstract class State {
public abstract void doSomething(Person person);
}
package com.ibeifeng.ex3;
public class SState extends State {
public void doSomething(Person person) {
if(person.getHour() == 18) {
System.out.println("吃晚饭");
} else {
person.setState(new NoState());
person.doSomething();
}
}
}
package com.ibeifeng.ex3;
public class NoState extends State {
public void doSomething(Person person) {
System.out.println(person.getHour() + "未定义");
}
}
package com.ibeifeng.ex3;
public class LState extends State{
public void doSomething(Person person) {
if(person.getHour() == 12) {
System.out.println("吃中饭");
} else {
person.setState(new SState());
person.doSomething();
}
}
}
package com.ibeifeng.ex3;
public class MState extends State {
public void doSomething(Person person) {
if(person.getHour() == 7) {
System.out.println("吃早餐");
} else {
person.setState(new LState());
person.doSomething();
}
}
}
package com.ibeifeng.ex3;
public class Person {
private int hour;
private State state;
public int getHour() {
return hour;
}
public void setHour(int hour) {
this.hour = hour;
}
public Person() {
state = new MState();
}
public void doSomething(){
// if(hour == 7) {
// state = new MState();
// state.doSomething();
// } else if(hour == 12) {
// state = new LState();
// state.doSomething();
// } else if(hour == 18) {
// state = new SState();
// state.doSomething();
// } else {
// state = new NoState();
// state.doSomething();
// }
state.doSomething(this);
//复位,都所以方法以后再执行。
state = new MState();
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
}
package com.ibeifeng.ex3;
public class MainClass {
public static void main(String[] args) {
Person person = new Person();
person.setHour(7);
person.doSomething();
person.setHour(12);
person.doSomething();
person.setHour(18);
person.doSomething();
person.setHour(8);
person.doSomething();
person.setHour(7);
person.doSomething();
person.setHour(18);
person.doSomething();
}
}