使用状态模式来维护当前所选对象是否很好?

时间:2018-09-13 18:17:18

标签: c++ oop design-patterns state

典型的状态模式方案包括状态大不相同的状态,例如closed_connection_stateopen_connection_state。就我而言,所有状态基本上都相同,但是该操作需要应用于当前选定的对象。

通常情况下,这样的操作是使用指向当前所选对象的索引变量完成的,但使用状态模式是一种更好的实现方式,例如下面的示例?

class Object
{
    std::string _name;
public:
    Object(std::string name) : _name(name)
    {

    }

    void Perform()
    {
        std::cout << _name << " Perform called\r\n";
    }
};

class CurrentObject
{
    Object* _a;
    Object* _b;
    Object* _current;

public:

    CurrentObject(Object* a, Object* b) : _a(a), _b(b)
    {
        _current = a;
    }

    void Perform()
    {
        _current->Perform();

        // Update _current logic goes here, lets just switch
        // the state whenever `Perform` is called.
        if (_current == _a)
            _current = _b;
        else
            _current = _a;
    };

};

int main()
{
    Object a("a"); // program can be in a state when `a` is the current object.
    Object b("b"); // or b can become the current object as result of an operation on current object

    CurrentObject current(&a, &b); // it assigns the defaults

    // assume Perform() does its thing but it also needs to change the current selected object.
    // In this example, we assumes the current selection object is always swapped.
    current.Perform(); // operates on `a`, the default
    current.Perform(); // operates on `b` due state changed in above line
    current.Perform(); // operates on `a` doe to state changed in above line again
}

1 个答案:

答案 0 :(得分:2)

这绝对是一件合理的事情,如果您的状态成倍增加(因为状态机趋向于此),这可能会变得很难维护,但这实际上是状态机的非常好的OO风格实现。

您可能希望状态(a和b)扩展一个公共的抽象状态,以便在所有状态下的功能相同时,您不必在每个对象中都实现它。

对于扩展,您可能还想“命名”您的状态并将其放入哈希表中,一旦扩展(记住,在编程中您有1个或多个),添加新状态就不会对状态进行代码更改机器-但我认为您已经有了类似的东西,只是缩小了问题的范围。

还请注意,要切换状态(您不希望直接进行更改)(如您的示例),您可能需要一个方法(setState),该方法在执行方法返回时更改状态,而不是在执行方法本身或同时执行它正在运行。实际上,您可以执行perform返回一个字符串,指示它的下一个所需状态。

根据评论进行编辑:

我命名您的州的意思是:

class CurrentObject
{
    Object* _a;
    Object* _b;
    Object* _current;
    ...

您可能会有类似的东西(对不起,我的Java语法,C#不是我的主要语言,但我知道它的功能非常相似)

class CurrentObject
{
    Hashtable states=new Hashtable();
    Object* _current;

    public addState(String stateName, Object* state)
    {
        states.put(stateName, state)
    }

    public void Perform()
    {
        String nextState = _current->Perform();
        if(nextState != null)
            setState(nextState);
    }
    public void setState(String stateName)
    {
        _current = states.get(stateName);
    }

}

您的调用代码将执行以下操作:

currentObject = new CurrentObject()
currentObject.addState("state a", _a);
currentObject.addState("state b", _b); 
currentObject.setState("state a");
currentObject.perform();
...

我忽略了很多初始化和错误检查。

您的状态机当前仅具有一个事件:“ Perform()”。您可能会发现需要其他事件,这会使事情复杂化(在Java中,我可能会使用反射或注释来解决该问题,不确定C#会怎么做)。