状态模式容许一个对象在其内部状态改变时改变它的行为,对象看起来彷佛修改了它所属的类,属于行为型模式。 bash
优势:ide
缺点:spa
定义抽象状态角色ConnectStatecode
public interface ConnectState {
void handleAction();
}
复制代码
定义具体状态角色ReconnectStatecdn
public class ReconnectState implements ConnectState {
@Override
public void handleAction() {
// 重连逻辑
}
}
复制代码
定义具体状态角色SuccessState对象
public class SuccessState implements ConnectState {
@Override
public void handleAction() {
// 成功逻辑
}
}
复制代码
定义具体状态角色FailureStateblog
public class FailureState implements ConnectState {
@Override
public void handleAction() {
// 失败逻辑
}
}
复制代码
定义环境角色Context接口
public class Context {
private ReconnectState reconnectState;
private FailureState failureState;
private SuccessState successState;
public void reconnect() {
if (reconnectState == null) {
reconnectState = new ReconnectState();
}
reconnectState.handleAction();
}
public void failure() {
if (failureState == null) {
failureState = new FailureState();
}
failureState.handleAction();
}
public void success() {
if (successState == null) {
successState = new SuccessState();
}
successState.handleAction();
}
}
复制代码