状态(State)模式:对有状态的对象,把复杂的“判断逻辑”提取到不同的状态对象中,允许状态对象在其内部状态发生改变时改变其行为。
状态模式包含以下主要角色:
比如我们的会议有以下状态:待创建、待开始、进行中、已结束状态;我们的代码如下:
/**
* 状态接口
*/
public interface MeetingStateInterface {
//当前状态
void state();
//下一个状态
MeetingStateInterface next();
}
public class WaitCreateMeetingState implements MeetingStateInterface{
@Override
public void state() {
System.out.println("当前在待创建状态");
}
@Override
public MeetingStateInterface next() {
return new WaitStartMeetingState();
}
}
public class WaitStartMeetingState implements MeetingStateInterface{
@Override
public void state() {
System.out.println("待开始状态");
}
@Override
public MeetingStateInterface next() {
return new ProcessingMeetingState();
}
}
public class ProcessingMeetingState implements MeetingStateInterface{
@Override
public void state() {
System.out.println("会议进行中状态");
}
@Override
public MeetingStateInterface next() {
return new EndMeetingState();
}
}
public class EndMeetingState implements MeetingStateInterface{
@Override
public void state() {
System.out.println("已结束会议状态");
}
@Override
public MeetingStateInterface next() {
return null;
}
}
会议类如下:
public class Meeting {
private MeetingStateInterface meetingState;
public void setMeetingState(MeetingStateInterface meetingState) {
this.meetingState = meetingState;
}
//会议当前状态
public void state(){
meetingState.state();
}
//下一个状态
public void nextState(){
if(this.meetingState != null){
this.meetingState = this.meetingState.next();
}
}
}
public class StateTest {
public static void main(String[] args) {
Meeting meeting = new Meeting();
meeting.setMeetingState(new WaitCreateMeetingState());
meeting.state();
meeting.nextState();
meeting.state();
meeting.nextState();
meeting.state();
meeting.nextState();
meeting.state();
meeting.nextState();
}
}
运行结果如下:
状体模式一定要有状态切换。