狀態模式容許一個對象在其內部狀態改變時改變它的行爲,對象看起來彷佛修改了它所屬的類,屬於行爲型模式。 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();
}
}
複製代碼