zoukankan      html  css  js  c++  java
  • 设计模式——状态模式

    状态模式主要用在对象的状态随外界因数而改变,对象的状态改变后其动作也随之改变。通常设计状态机的时候会用到。

    #include <stdio.h>
    #include <unistd.h>
    #include <string.h>
    #include <iostream>

    using namespace std;
    class war;
    class state{
    public:
    virtual void fighting(war *pwar) = 0;
    virtual ~state(){};
    state(){};
    };

    class war{
    int ndays;
    state *m_curstate;
    public:
    war(state *ste)
    {
    m_curstate = ste;
    ndays = 0;
    }
    void setDay(int day) {
    ndays = day;
    }
    int getDay() {
    return ndays;
    }
    void getState() {
    m_curstate->fighting(this);
    }
    void setState(state *ste) {
    if (m_curstate) delete m_curstate;
    m_curstate = ste;
    }
    };

    class endState : public state {

    void fighting(war *pwar)
    {
    cout << "老大:"刚开始是哪个小混蛋挑事的,拉出来。妹的,你轻点包扎,疼死了。"" <<endl;
    cout << "老大:"这个护士业务能力好差,拉出去让小弟们解解乏。"" <<endl;
    }
    };

    class tailState : public state {
    void fighting(war *pwar)
    {
    cout << "士兵乙:"老大,他们去拿砍刀了。"" <<endl;
    cout << "老大:"兄弟们,撤!"" << endl;

    if (pwar->getDay() >= 10)
    {
    pwar->setState(new endState());
    }
    }
    };

    class middleState : public state{

    void fighting(war *pwar)
    {
    cout << "士兵甲:"老大,好多兄弟们受伤了。"" << endl;
    cout << "老大:"兄弟们坚持住,对方快坚持不住了。"" << endl;
    if (pwar->getDay() >= 7)
    {
    pwar->setState(new tailState());
    }
    }

    };


    class beginState : public state{
    void fighting(war *pwar)
    {
    cout << "老大:"兄弟们抄家伙,干死他们!"" << endl;

    if (pwar->getDay() >= 4)
    {
    pwar->setState(new middleState());
    }
    }
    };

    class preState : public state{
    void fighting(war *pwar)
    {
    cout << "有个士兵向领导报告:"老大,有人挑事!"" <<endl;
    if (pwar->getDay() >= 3)
    {
    pwar->setState(new beginState());
    }
    }
    };

    int main()
    {
    preState *pre = new preState();
    war westWar(pre);

    for (int n = 0; n < 15; n++)
    {
    westWar.getState();
    westWar.setDay(n);
    sleep(10);
    }
    return 0;
    }

  • 相关阅读:
    Lodash之throttle(节流)与debounce(防抖)总结
    css伪类:before及:after除了插入文字内容还能做点儿啥?画图
    一点对Promise的理解与总结
    前端开发常用网站汇总
    一分钟配置好JDK
    启动任务管理器命令符,doc命令
    判断是否是质数以及类型的转换
    图片数字型的九九乘法表
    1000以内的质数的方法,判断年份是否是闰年,打印水仙花数
    持续交付8-数据管理
  • 原文地址:https://www.cnblogs.com/tjyuanxi/p/9377566.html
Copyright © 2011-2022 走看看