解决的问题:无限的if elseif else
基本版:
package state;
public class V1 {
public static void main(String[] args) {
SayHi sayhi = new SayHi();
sayhi.setTime(1);
sayhi.doAction();
sayhi.setTime(9);
sayhi.doAction();
sayhi.setTime(16);
sayhi.doAction();
sayhi.setTime(20);
sayhi.doAction();
}
}
//打招呼的类
class SayHi {
Integer time;
public Integer getTime() {
return time;
}
public void setTime(Integer time) {
this.time = time;
}
public void doAction() {
if((time >= 0 && time < 4) || (time >= 19 && time <= 24)) {
System.out.println("晚上好!");
}else if(time >= 4 && time < 12) {
System.out.println("上午好!");
}else if(time >= 12 && time < 19) {
System.out.println("下午好!");
}
}
}
状态模式版本:
package state;
public class V2 {
public static void main(String[] args) {
SayHi2 sayhi = new SayHi2();
sayhi.setTime(1);
sayhi.doAction();
sayhi.setTime(9);
sayhi.doAction();
sayhi.setTime(16);
sayhi.doAction();
sayhi.setTime(20);
sayhi.doAction();
}
}
//环境类 也就是存放状态的类
class SayHi2 {
private Integer time;
private State state;
public SayHi2() {
state = new EveningState();
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public Integer getTime() {
return time;
}
public void setTime(Integer time) {
this.time = time;
this.setState(new EveningState());
}
public void doAction() {
state.doAction(this);
}
}
interface State {
void doAction(SayHi2 sayHi2);
}
class EveningState implements State {
@Override
public void doAction(SayHi2 sayHi2) {
if((sayHi2.getTime() >= 0 && sayHi2.getTime() < 4) || (sayHi2.getTime() >= 19 && sayHi2.getTime() <= 24)) {
System.out.println("晚上好!");
}else {
sayHi2.setState(new MorningState());
sayHi2.doAction();
}
}
}
class MorningState implements State {
@Override
public void doAction(SayHi2 sayHi2) {
if(sayHi2.getTime() >= 4 && sayHi2.getTime() < 12) {
System.out.println("上午好!");
}else {
sayHi2.setState(new AfternoonState());
sayHi2.doAction();
}
}
}
class AfternoonState implements State {
@Override
public void doAction(SayHi2 sayHi2) {
if(sayHi2.getTime() >= 12 && sayHi2.getTime() < 19) {
System.out.println("下午好!");
}else {
System.out.println("我与您有时间差,不知道怎么向你打招呼");
}
}
}
状态接口uml图: