Design pattern Start-state mode

Source: Internet
Author: User

State mode

First, the definition:

Allows change of behavior when an object's internal state changes, implementing state changes

Second, the role

The main solution is that when the conditional expression of a state transition is too complex, the judgment of the state is transferred to a series of classes of different states, simplifying the complex judgment.

Three, class diagram:

Iv. Realization OF

The 1.work class is used to implement the transformation state, state judgment, and the program that runs the corresponding state is also the interface that the user calls.

 Public classWork {State state ;  PublicWork () { This. State =NewFornoon (); }    Private inthour;  Public intGethour () {return  This. hour; }     Public voidSethour (inthour) {         This. Hour =hour; }     Public voiddoWork () { This. State.dowork ( This); }     Public voidsetState (state state) { This. State =State ; }}
View Code

2.state class actual operation, call the work of the state switch

 Public Abstract class State {    publicabstractvoid  doWork;}
View Code

Implementation class of 3.state

 Public classAfternoonextendsState {@Override Public voiddoWork (Work work) {if(Work.gethour () > 12) {System.out.println ("In the Afternoon"); }        Else{work.setstate (NewFornoon ());        Work.dowork (); }    }} Public classFornoonextendsState {@Override Public voiddoWork (Work work) {if(Work.gethour () < 12) {System.out.println ("In the Morning"); }        Else{work.setstate (Newafternoon ());        Work.dowork (); }    }}
View Code

4. Customer Class Test class

 Public class Client {    publicstaticvoid  main (string[] args)    {        new work ();        Work.sethour (+);        Work.dowork ();        Work.sethour (+);        Work.dowork ();    }}
View Code

Design pattern Start-state mode

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.