zoukankan      html  css  js  c++  java
  • 设计模式之状态模式(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;
    }
    
  • 相关阅读:
    Fedora下使用minicom及USB串口线
    fedora装机后要运行的脚本(原创)
    终极 Shell
    深入学习 Git 工作流
    如何使用Git上传项目代码到github
    Fedora23 chrome 安装
    Fedora下安装deb包方法
    vim自动缩进设置
    Fedora 20 安装搜狗拼音输入法
    C语言stat()函数:获取文件状态
  • 原文地址:https://www.cnblogs.com/liuweilinlin/p/3209766.html
Copyright © 2011-2022 走看看