Skip to content

Latest commit

 

History

History
123 lines (101 loc) · 2.95 KB

16.状态模式.md

File metadata and controls

123 lines (101 loc) · 2.95 KB

状态模式 State

  • 将所有与一个特定状态相关的行为都放入一个State的子类对象中,在对象状态切换时,切换相应的对象;但是同时维持State的接口,这样实现了具体操作与状态转换之间的解耦
  • 为不同的状态引入不同的对象使得状态转换变得更加明确,而且可以保证不会出现状态不一致的情况,因为转换是原子性的
  • 如果State对象没有实例变量,各个上下文可以共享同一个State对象,从而节省对象开销

动机

在软件构建过程中,某些对象的状态如果改变,其行为也会随之而发生变化,比如文档处于只读状态,其支持的行为和读写状态支持的行为就可能完全不同。

模式定义

允许一个对象在其内部状态改变时改变它的行为,从而使对象看起来似乎修改了其行为。

代码

原始设计

enum NetworkState
{
    Network_Open,
    Network_Close,
    Network_Connect,
+   Network_Wait
};

class NetworkProcessor{
    NetworkState state;
public:
    void Operation1(){
        if(state == Network_Open){
            //...
            state = Network_Close;
        }else if(state == Network_Close){
            //...
            state = Network_Connect;
        }else if(state == Network_Connect){
            //...
            state = Network_Open;
+        }else if(state == Network_Wait){
+            //...
+            state = Network_Open;
+        }
    }
    void Operation2(){
        if(state == Network_Open){
            //...
            state = Network_Connect;
        }else if(state == Network_Close){
            //...
            state = Network_Open;
        }else if(state == Network_Connect){
            //...
            state = Network_Close;
+        }else if(state == Network_Wait){
+            //...
+            state = Network_Open;
+        }        
    } 
};

重构设计

class NetworkState{
public:
    NetworkState* pNext;
    virtual void Operation1() = 0;
    virtual void Operation2() = 0;

    virtual ~NetworkState(){}
};

class OpenState : public NetworkState{
    static NetworkState* m_instance;
public:
    static NetworkState* getInstacne(){
        if(m_instance == nullptr){
            m_instace = new OpenState();
        }
        return m_instacne;
    }

    void Operation1(){
        //...
        pNext = CloseState::getInstace();
    }

    void Operation2(){
        //...
        pNext = ConnectState::getInstace();
    }
};

class CloseState : public NetworkState{
    //...
};


class NetworkProcessor{
    NetworkState* pState;
public:
    NetworkProcessor(NetworkState* state) : pState(state){}

    void Operation1(){
        //...
        pState->Operation1();
        pState = pState->pNext;
    }
    void Operation2(){
        //...
        pState->Operation2();
        pState = pState->pNext;
    }
};

题目