/** * 状态模式:跟策略模式很像,只不过策略模式是根据行为来判断的,而状态模式是根据状态来判断的:例如猪有睡觉和醒来2种状态,睡觉就会做梦.醒来就会吃东西 * 模式特点:一个状态接口和多个状态实现类 ,一个上下文类,状态对象以组合的方式作为属性到上下文类中 * * * * */ //状态接口 public interface IState { void doSomething(); } //状态接口的实现类,睡觉状态 public class Sleep implements IState { @Override public void doSomething() { System.out.println("dreaming -----"); } } //状态接口实现类,醒来状态 public class Wake implements IState { @Override public void doSomething() { System.out.println("eating----"); } } //状态类,实现不同状态做不同事情 public class Pig { private IState state; public IState getState() { return state; } public void setState(IState state) { this.state = state; } public void doSomething(){ state.doSomething(); } } public class Test { public static void main(String[] args) { IState sleep = new Sleep(); IState wake = new Wake(); Pig pig = new Pig(); //猪睡觉的状态 pig.setState(sleep); pig.doSomething(); //猪醒来时的状态 pig.setState(wake); pig.doSomething(); } }