• 设计模式之状态模式(State)


    状态模式原理:随着状态的变化,对象的行为也发生变化

    代码如下:

    #include <iostream>
    #include <string>
    #include <list>
    using namespace std;
    
    class War;
    class State
    {
    public:
    	virtual void fire(War *war)
    	{
    		
    	}
    };
    
    class War
    {
    public:
    	War(State* state):m_state(state),m_day(0){}
    	void Setday(int day)
    	{
    		m_day = day;
    	}
    	int Getday()
    	{
    		return m_day;
    	}
    	void SetState(State *state)
    	{
    		delete m_state;
    		m_state = state;
    	}
    	void GetState()
    	{
    		m_state->fire(this);
    	}
    	~War(){delete m_state;}
    private:
    	State *m_state;
    	int m_day;
    };
    
    
    class WarEndState:public State
    {
    public:
    	virtual void fire(War *war)
    	{			
    		cout << "we are in the end of war" <<endl;		
    	}
    };
    
    class WarMiddleState:public State
    {
    public:
    	virtual void fire(War *war)
    	{
    		if (war->Getday() < 20)
    		{
    			cout << "we are in the middle of war" <<endl;
    		}
    		else
    		{
    			war->SetState(new WarEndState());
    			war->GetState();
    		}
    	}
    };
    
    class WarBeforeState:public State
    {
    public:
    	virtual void fire(War *war)
    	{
    		if (war->Getday() < 10)
    		{
    			cout << "we are in the before of war" <<endl;
    		}
    		else
    		{
    			war->SetState(new WarMiddleState());
    			war->GetState();
    		}
    	}
    };
    
    int main()
    {
    	War *war = new War(new WarBeforeState());
    	for (int i = 9;i < 30;i+=9)
    	{
    		war->Setday(i);
    		war->GetState();
    	}
    	return 0;
    }
    
  • 相关阅读:
    linux防火墙关闭与中文显示乱码排错
    linux基础命令
    盒子模块
    表的数据类型
    pymysql模块
    sql综合练习题
    pymysql内置功能
    数据操作
    vue 左侧菜单展示,以及对应的路由配置
    vue 左侧菜单路由实现
  • 原文地址:https://www.cnblogs.com/liuweilinlin/p/3209766.html
Copyright © 2020-2023  润新知