设计模式管理状态之state状态模式-以类表示状态

十九、state状态 以类表示状态

public interface State {
    void doClock(Context context,int hour);
    void doUse(Context context);
    void doAlarm(Context context);
    void doPhone(Context context);
}
public class DayState implements State{
    private static DayState singleton=new DayState();
    public static DayState getInstance(){
        return singleton;
    }

    private DayState() {
    }

    @Override
    public void doClock(Context context, int hour) {
        if (hour<9||17<=hour){
            context.changeState(NightState.getInstance());
        }
    }

    @Override
    public void doUse(Context context) {
        context.recordLog("使用金库(白天)");
    }

    @Override
    public void doAlarm(Context context) {
        context.callSecurityCenter("警铃(白天)");
    }

    @Override
    public void doPhone(Context context) {
        context.callSecurityCenter("一般通话白天");
    }
    public String toString(){
        return "[白天]";
    }
}
public class NightState implements State {
    private static NightState singleton=new NightState();
    public static State getInstance(){
        return singleton;
    }
    private NightState() {
    }

    @Override
    public void doClock(Context context, int hour) {
        if (9<=hour&&hour<=17){
            context.changeState(DayState.getInstance());
        }
    }

    @Override
    public void doUse(Context context) {
        context.callSecurityCenter("异常,晚间使用金库");
    }

    @Override
    public void doAlarm(Context context) {
        context.callSecurityCenter("警铃晚间");
    }

    @Override
    public void doPhone(Context context) {
        context.recordLog("晚间通话录音");
    }
    public String toString(){
        return "[晚间]";
    }
}
public interface Context {
    void setClock(int hour);
    void changeState(State state);
    void callSecurityCenter(String msg);
    void recordLog(String msg);
}

你可能感兴趣的:(设计模式)