状态模式
定义状态基类:
public interface State {
public void run();
public void sleep();
}
定义两个状态:
public class EnergeticState implements State {
public void run() {
System.out.print("跑得快");
}
public void sleep() {
System.out.print("睡不着");
}
}
public class TiredState implements State {
public void run() {
System.out.print("跑不动");
}
public void sleep() {
System.out.print("睡得香");
}
}
Person类中定义一个状态:
public class Person {
private State state = new TiredState();
public void setTried(boolean isTired) {
//提供一个方法修改State对象就可以控制Person的执行逻辑了
state = isTired ? new TiredState() : new EnergeticState();
}
public void run(){
state.run();
}
public void sleep(){
state.sleep();
}
}
使用:
Person person = new Person();
person.setTried(true); //通过flag来切换状态
person.run(); //跑不动
person.sleep(); //睡得香
策略模式:
与状态模式类似,只是不用状态Flag来修改策略,而是注入一个策略,还是用上面的例子:
public class Person {
private State state = new TiredState();
public void setState(State state) {
this.state = state;
}
public void run(){
state.run();
}
public void sleep(){
state.sleep();
}
}
使用:
Person person = new Person();
person.setState(new TiredState()); //通过注入切换策略
person.run(); //跑不动
person.sleep(); //睡得香
总结:
可以用在if else分支过多导致逻辑混乱的情况
缺点是每个状态(策略)都对应一个类,可能导致类型过多