状态模式


#include 
using namespace std;
class Work;

class State {
    
public:
    ~State(){};
    virtual void WriteProgram(Work * work){};
};

class ForenoonState: public State {
    
public:
    ~ForenoonState(){};
    void WriteProgram(Work * work);
};

class NoonState:public State {
    
public:
    ~NoonState(){};
    void WriteProgram(Work * work);
};

class Work {
private:
    State  * current;
    double hour;
    
    bool finish = false;
    
public:
    Work(){current = new ForenoonState(); }
    double getHour(){return  hour;}
    void setHour(double hour){this->hour = hour;
        if (hour > 10) {
            current = new NoonState();
        } else {
            current = new ForenoonState();
        }
    }
    bool getFinish(){return  finish;}
    void setFinish(bool finish){this->finish = finish;}
    State *  getState(){return  current;}
    void setState(State * state){this->current = state;}
    
    void WriteProgram(){current->WriteProgram(this);}
};

//.m
void ForenoonState::WriteProgram(Work *work) {
    cout<< "it is"<getHour()<<"i want to start work"<getHour()<<"i want to finish work"<

    Work * emergencyProject = new Work();
    emergencyProject->setHour(5);
    emergencyProject->WriteProgram();
    emergencyProject->setHour(30);
    emergencyProject->WriteProgram();

状态模式主要解决的是当控制一个对象状态转换的条件表达式过于复杂时的情况。将状态的判断逻辑转移到表示不同状态的一系列类中可以把复杂的判断逻辑简化。

好处就是将与特定状态的相关行为局部化,并且将不同状态的行为分割开来。

当一个对象的行为取决于它的状态,并且它必须在运行时刻根据状态改变它的行为时,就可以考虑使用状态模式了。

你可能感兴趣的:(状态模式)