状态模式(State Pattern)中,对象的行为依赖于它的状态(属性),类的行为是随着类自身的状态改变而改变。常用于if...else分支语句,但状态不宜太多。
一、需求举例:
1.当工程师处于忙碌状态时,不接受新的项目开发需求;
2.当工程师处于不忙状态时,接受新的项目开发需求。
二、类图
三、代码实例
1.状态父类:State
package com.lance.state;
public abstract class State {
public static final String BUSY = "busy";
public static final String IDLE = "idle";
protected String state;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public void exe(EngineerContext context) {
System.out.println("do default.");
}
}
2.忙工程师类:BusyEngineer
package com.lance.state;
public class BusyEngineer extends State {
public BusyEngineer(String state) {
this.state = state;
}
@Override
public void exe(EngineerContext context) {
System.out.println("Engineer is busy refuse new project requirements.");
context.setState(this);
}
}
3.空闲工程师类:IdleEngineer
package com.lance.state;
public class IdleEngineer extends State {
public IdleEngineer(String state) {
this.state = state;
}
@Override
public void exe(EngineerContext context) {
System.out.println("Engineer is idle accept new project requirements.");
context.setState(this);
}
}
4.上下文类:EngineerContext
package com.lance.state;
public class EngineerContext {
private State state;
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
}
5.主类:StatePattern
package com.lance.state;
public class StatePattern {
public static void main(String[] args) {
System.out.println("==========start==========");
EngineerContext engineerContext = new EngineerContext();
State state = new IdleEngineer(State.IDLE);
state.exe(engineerContext);
System.out.println("current state:" + engineerContext.getState().getState());
System.out.println("=======================");
state = new BusyEngineer(State.BUSY);
state.exe(engineerContext);
System.out.println("current state:" + engineerContext.getState().getState());
System.out.println("==========end==========");
}
}
输出结果:
==========start==========
Engineer is idle accept new project requirements.
current state:idle
=======================
Engineer is busy refuse new project requirements.
current state:busy
==========end==========
网友评论