Role:
Allows an object to change its behavior when its internal state changes.
UML Structure diagram:
Analytical:
The state model mainly solves the problem of different processing operation according to different states, which is often encountered in the development, and most people use switch-case statements to deal with this problem, which causes a problem: too many branches, And if you add a new state, you need to compile the original code. The state pattern deals with such problems in a way that encapsulates these different states, processes them when the status changes, and then switches to another state, which means that the state's switching responsibility is assigned to the specific State class. Meanwhile, The state pattern and the strategy pattern have many similarities in the diagram, and it needs to be explained that the two ideas are consistent, except that they are encapsulated in different states, and the stategy pattern encapsulates different algorithms.
Realize:
1) State.h
/**//********************************************************************
created:2006/08/05
fil Ename:state.h
Author: Lee Chuang
http://www.cppblog.com/converse/
Purpose: Demo code for State mode
*********************************************************************/
#ifndef state_h
#define STATE_H
class state;
Class Context
{
Public:
Context (state* pstate);
~context ();
void Request ();
void Changestate (state *pstate);
Private:
State *m_pstate;
};
Class State
{
Public:
Virtual ~state () {}
virtual void Handle (context* pContext) = 0 ;
};
Class Concreatestatea
: Public State
{
Public:
void Handle (context* pContext);
};
Class Concreatestateb
: Public State
{
Public:
void Handle (context* pContext);
};
#endif