C + + design mode shallow knowledge state mode

Source: Internet
Author: User
State mode: When an object's internal state changes to allow its behavior to change, the object looks like it has changed its class.

State mode mainly solves the situation when the conditional expression that controls an object state transition is too complex. By transferring the judgment logic of the state to a series of classes representing different States, complex judgments can be logically made.

Pattern implementation:

[Code]class context;class state{public:    virtual void Handle (Context *pcontext) = 0;}; Class Concretestatea:public State{public:    virtual void Handle (Context *pcontext) {        std::cout << ' I ' m Concretestatea.\n ";    }}; Class Concretestateb:public State{public:    virtual void Handle (Context *pcontext) {        std::cout << ' I ' m Concretestateb.\n ";    }}; Class Context{public:    Context (State *state):p State {}    void Request () {        if (pState) {            pstate- >handle (this);        }    }    void Changestate (state *pstate) {        pstate = pstate;    } Private: State    *pstate;};

Client

[Code]int Main () {state    *pstate = new Concretestatea ();    Context *context = new context (pState);    Context->request ();  Output:i ' m concretestatea.    state *pstate2 = new Concretestateb ();    Context->changestate (PSTATE2);    Context->request ();  Output:i ' m concretestateb.    if (pState) {        delete pState;        PState = NULL;      }    if (pState2) {        delete pState2;        PState2 = NULL;    }    if (context) {        Delete context;        context = NULL;    }    return 0;}

The above is the C + + design mode of shallow knowledge of the content of State mode, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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: info-contact@alibabacloud.com 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.