繁体   English   中英

如何实现 State 设计模式?

[英]How to implement the State design pattern?

假设我将在有限的 state 机器之后实现(在 C++ 中),该机器由 5 个状态组成,其中状态之间的转换基于 6 个 boolean 标志的值发生。 在每个状态中,只有 boolean 标志总数中的几个是相关的,例如,在 State_A 中,到State_A的转换State_B以下条件: flag_01 == true && flag_02 == true和 rest 的值标志无关紧要。

在此处输入图像描述

我想利用 State 设计模式来实现 state 机器在此处输入图像描述

不幸的是,我一开始就卡住了。 即为所有 state 子类定义公共基础 class 的接口。 在我看来,我的情况与文献中提到的示例略有不同,其中 state 转换基于具有保护条件的单个事件发生。 在我的情况下,状态之间的转换基于具有多个操作数的逻辑表达式发生,任何人都可以给我一个建议如何定义公共基础 class 的接口吗?

您可以创建一些减速器来决定 state 应该是用户。 让我通过 C# 展示一个示例。

这是 state 的抽象:

public interface IAtmMachineState
{
    void Execute();
}

及其具体状态:

public class WithdrawState : IAtmMachineState
{
    public void Execute()
    {
        Console.WriteLine("You are taking money");
    }
}

public class DepositState : IAtmMachineState
{
    public void Execute()
    {
        Console.WriteLine("You are putting money");
    }
}

public class SleepState : IAtmMachineState
{
    public void Execute()
    {
        Console.WriteLine("Insert your card");
    }
}

这是 state 的上下文:

public class AtmStateContext
{
    private IAtmMachineState _currentState;

    public AtmStateContext()
    {
        _currentState = new SleepState();
    }

    public void SetState(IAtmMachineState currentState)
    { 
        _currentState = currentState;
    }

    public void Execute() 
    {
        _currentState.Execute();
    }
}

这是一个可以带参数的reducer:

public class StateReducer
{
    public IAtmMachineState Get(int a, string b) 
    {
        if (a == 0)
            return new WithdrawState();
        else if (!string.IsNullOrEmpty(b))
            return new DepositState();

        return new SleepState();
    }
}   

它可以像这样使用:

AtmStateContext atmState = new AtmStateContext();
StateReducer stateReducer = new StateReducer();

atmState.SetState(stateReducer.Get(1, ""));
atmState.Execute(); // OUTPUT: insert your card

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM