Analysis and implementation of design patterns (c + +) 17-state mode

Source: Internet
Author: User


Allows an object to change its behavior when its internal state changes.

UML Structure diagram:


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.


1) State.h

fil    Ename:state.h
Author: Lee Chuang

Purpose: Demo code for State mode

#ifndef state_h
#define STATE_H

class state;
Class Context
Context (state* pstate);
~context ();
void Request ();
void Changestate (state *pstate);

State *m_pstate;

Class State
Virtual ~state () {}

virtual void Handle (context* pContext) = 0 ;

Class Concreatestatea
: Public State
void Handle (context* pContext);

Class Concreatestateb
: Public State
void Handle (context* pContext);


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.