设计模式学习小结(3.3)——状态模式

作用:

对象内部分多种状态,并且在各种状态下可以互相切换。

例子:

汽车,可以在停止、启动、运行之间切换。

示例代码:

CarState.h

#ifndef _CAR_STATE_H_
#define _CAR_STATE_H_

class CarContext;

class CarState
{
public:
	virtual ~CarState(void);
	//需要做以下几件事:
	//1.修改CarContext状态
	//2.进行自己的操作
	virtual void ChangeState(CarContext* con) = 0;
protected:
	CarState(void);
};

class CarStop : public CarState
{
public:
	CarStop();
	~CarStop();
	void ChangeState(CarContext* con);
};

class CarStart : public CarState
{
public:
	CarStart();
	~CarStart();
	void ChangeState(CarContext* con);
};

class CarRunnng : public CarState
{
public:
	CarRunnng();
	~CarRunnng();
	void ChangeState(CarContext* con);
};

#endif


CarState.cpp

#include "CarState.h"
#include "CarContext.h"
#include <iostream>

using namespace std;

CarState::CarState(void)
{
}


CarState::~CarState(void)
{
}

CarStop::CarStop()
{

}

CarStop::~CarStop()
{

}

void CarStop::ChangeState(CarContext* con)
{
 cout<<"Car Stop-->Start"<<endl;
 //设置CarContext新状态
 //new的指针必须用delete删除
 con->SetState(new CarStart());
}

CarStart::CarStart()
{

}

CarStart::~CarStart()
{

}

void CarStart::ChangeState(CarContext* con)
{
 cout<<"Car Start-->Running"<<endl;
 //new的指针必须用delete删除
 con->SetState(new CarRunnng());
}

CarRunnng::CarRunnng()
{

}

CarRunnng::~CarRunnng()
{

}

void CarRunnng::ChangeState(CarContext* con)
{
 cout<<"Car Running-->Stop"<<endl;
 //new的指针必须用delete删除
 con->SetState(new CarStop());
}



 

CarContext.h

#pragma once

class CarState;

class CarContext
{
public:
	CarContext(CarState* state);
	~CarContext(void);
	void ChangeState();
	void SetState(CarState* state);
private: 
	CarState* m_state;
};

CarContext.cpp

#include "CarContext.h"
#include "CarState.h"
#include <iostream>

CarContext::CarContext(CarState* state)
{
	m_state = state;
}


CarContext::~CarContext(void)
{
	if (NULL == m_state)
	{
		return;
	}
	delete m_state;
}

void CarContext::ChangeState()
{
	m_state->ChangeState(this);
}

void CarContext::SetState( CarState* state )
{
	//因为在State类中声明了新指针
	//为防止内存泄漏,所以在此需delete原state指针
	if (NULL == m_state)
	{
		m_state = state;
	}
	delete m_state;
	m_state = state;
}


main.cpp

#include "CarContext.h"
#include "CarState.h"
#include <iostream>

void main()
{
	CarState* state = new CarStop();
	CarContext* con = new CarContext(state);
	con->ChangeState();
	con->ChangeState();
	con->ChangeState();
	con->ChangeState();
	con->ChangeState();
	con->ChangeState();
	con->ChangeState();
	con->ChangeState();
	con->ChangeState();
	delete con;
	system("pause");
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值