C++设计模式之状态模式

//状态模式,当一个对象的内在状态改变时,语序改变其行为,这个对象看起来像是改变了其类
#include<iostream>
using namespace std;

class State;
class Forenoon;
class Noon;
class Afternonn;
class Evening;
class GoHome;
class Work;

class State
{
public:
    virtual void writeprogram(Work* w) = 0;
};

class Work
{
    State* current;
public:
    double hours;
    bool finish;
    Work();
    void SetState(State* s)
    {
        current = s;
    }
    void WorkProgram()
    {
        current->writeprogram(this);
    }
};

class Forenoon :public State
{
public:
    void writeprogram(Work* w);
};

class Noon :public State
{
public:
    void writeprogram(Work* w);
};

class Afternoon :public State
{
public:
    void writeprogram(Work* w);
};

class Evening :public State
{
public:
    void writeprogram(Work* w);
};

class GoHome :public State
{
public:
    void writeprogram(Work* w)
    {
        cout << "当前时间:" << w->hours << "点,下班回家" << endl;
    }
};

Work::Work()
{
    finish = false;
    current = new Forenoon();
}

void Forenoon::writeprogram(Work* w)
{
    if (w->hours < 12)
    {
        cout << "当前时间:" << w->hours << "点,上午工作,精神百倍" << endl;
    }
    else
    {
        w->SetState(new Noon());
        w->WorkProgram();
    }
}

void Noon::writeprogram(Work* w)
{
    if (w->hours < 13)
    {
        cout << "当前时间:" << w->hours << "点,吃午饭,睡午觉" << endl;
    }
    else
    {
        w->SetState(new Afternoon());
        w->WorkProgram();
    }
}

void Afternoon::writeprogram(Work* w)
{
    if (w->hours < 17)
    {
        cout << "当前时间:" << w->hours << "点,下午状态还不错" << endl;
    }
    else
    {
        w->SetState(new Evening());
        w->WorkProgram();
    }
}

void Evening::writeprogram(Work* w)
{
    if (w->finish)
    {
        w->SetState(new GoHome());
        w->WorkProgram();
    }
    else
    {
        cout << "当前时间:" << w->hours << "点,加班好嘞" << endl;
    }
}

int main()
{
    Work* work = new Work();
    work->hours = 10;
    work->WorkProgram();

    work->hours = 12;
    work->WorkProgram();

    work->hours = 15;
    work->WorkProgram();

    work->finish = true;
    work->hours = 18;
    work->WorkProgram();

    system("pause");
    return 0;
}

运行结果:

当前时间:10点,上午工作,精神百倍
当前时间:12点,吃午饭,睡午觉
当前时间:15点,下午状态还不错
当前时间:18点,下班回家
请按任意键继续. . .

这个程序在逻辑上是不通顺的,但是能表达出状态函数的作用,基本思路是这样的:
定义状态接口,在状态接口定义由于状态转移所产生的变化,即那个虚函数。
定义对象Work,Work中包含了几个部分
引入状态,状态转移的判断条件函数,状态转移的操作函数。就是这个样子

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